Compare commits
34
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
db64ded3f0 | ||
|
|
fe35a9cf68 | ||
|
|
ad76ce9cdc | ||
|
|
ced96a57b3 | ||
|
|
302a9f4e54 | ||
|
|
69ed608241 | ||
|
|
9da8ea1dec | ||
|
|
2b4a18385d | ||
|
|
c9f003dadd | ||
|
|
a447a9f615 | ||
|
|
87d3f6a0a1 | ||
|
|
f2705eeb57 | ||
|
|
ac37d2c73f | ||
|
|
e00ea624cd | ||
|
|
20b62c42e3 | ||
|
|
59971991c7 | ||
|
|
a629681ae5 | ||
|
|
572d5fb5ec | ||
|
|
91a1858743 | ||
|
|
f00d3627c9 | ||
|
|
7760e01ccb | ||
|
|
efd37dca93 | ||
|
|
796c679140 | ||
|
|
76fd4c5fb1 | ||
|
|
68f24e34d5 | ||
|
|
22d7ebab50 | ||
|
|
4f5f3e14a1 | ||
|
|
dbf021e04a | ||
|
|
cc24f070db | ||
|
|
0b663a7fc6 | ||
|
|
ff1e4c1381 | ||
|
|
21bb20ce0c | ||
|
|
92b75cb924 | ||
|
|
1ea008b71c |
No files matched your search
@@ -33,6 +33,7 @@ body:
|
||||
options:
|
||||
# The below comment is used to insert a new version with on-release.yml
|
||||
#NEXT_VERSION#
|
||||
- 1.64.0
|
||||
- 1.62.0
|
||||
- 1.61.0
|
||||
- 1.60.1-beta.1
|
||||
|
||||
@@ -1,3 +1,67 @@
|
||||
## [1.64.0](https://github.com/homarr-labs/homarr/compare/v1.63.0...v1.64.0) (2026-06-05)
|
||||
|
||||
### Features
|
||||
|
||||
* add comprehensive demo mode with mock integrations ([#5870](https://github.com/homarr-labs/homarr/issues/5870)) ([0a64679](https://github.com/homarr-labs/homarr/commit/0a6467979a5e3b3e3eae6252c31fca1d9af54dc1))
|
||||
* add PeaNUT integration and UPS monitoring widget ([#5862](https://github.com/homarr-labs/homarr/issues/5862)) ([0dc2558](https://github.com/homarr-labs/homarr/commit/0dc2558fafedcbba246c2e968d00cc541ab9f84e))
|
||||
* **docker:** add container logs modal and stats columns ([#4807](https://github.com/homarr-labs/homarr/issues/4807)) ([dbf021e](https://github.com/homarr-labs/homarr/commit/dbf021e04a785b44ad0e2ce45634de371d76de6d))
|
||||
* media request search as first-class spotlight mode ([#5823](https://github.com/homarr-labs/homarr/issues/5823)) ([3d3e305](https://github.com/homarr-labs/homarr/commit/3d3e3059a98b36b6e64e3aad90f715e334baff3e))
|
||||
* **onboarding:** enhance integration setup with Docker discovery and URL templating ([#5607](https://github.com/homarr-labs/homarr/issues/5607)) ([dd7a490](https://github.com/homarr-labs/homarr/commit/dd7a4908a36a71c1d0d1e41524eb8fd9bf53ca4d))
|
||||
* **onboarding:** guided management and board tours ([#5756](https://github.com/homarr-labs/homarr/issues/5756)) ([0b663a7](https://github.com/homarr-labs/homarr/commit/0b663a7fc6c017b9fbe78c019f06d46ee95f165f))
|
||||
* **widgets:** add in-place app editing in widget edit modal ([#5809](https://github.com/homarr-labs/homarr/issues/5809)) ([99346f2](https://github.com/homarr-labs/homarr/commit/99346f288bcfc701c41fecaab6f7bc0438d80563))
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* add bookmark widget option to toggle card borders ([#5854](https://github.com/homarr-labs/homarr/issues/5854)) ([41fe592](https://github.com/homarr-labs/homarr/commit/41fe5928f19207d02b04e64c2caac49d896f72ce))
|
||||
* **auth:** relax password complexity requirements to suggestions-only ([#5764](https://github.com/homarr-labs/homarr/issues/5764)) ([fd10788](https://github.com/homarr-labs/homarr/commit/fd107888385557ededcf51576c6320a1960690f2))
|
||||
* **db:** log when UNSAFE_ENABLE_MOCK_INTEGRATION is enabled during seeding ([efd37dc](https://github.com/homarr-labs/homarr/commit/efd37dca93be7f5f362331e9b5c2a95a87e24379))
|
||||
* disable onboarding tours when demo mode is enabled ([68f24e3](https://github.com/homarr-labs/homarr/commit/68f24e34d580e3a155c37ca37c3ffd61f296bd0c))
|
||||
* **docker:** restore container selection toolbar broken by Mantine v9 ([#5855](https://github.com/homarr-labs/homarr/issues/5855)) ([fe4598f](https://github.com/homarr-labs/homarr/commit/fe4598f7221a2861b8c5ae0cfd267e8c4fbf48df))
|
||||
* **immich:** respect app color scheme in server-stats widget ([#5859](https://github.com/homarr-labs/homarr/issues/5859)) ([2c6b7a8](https://github.com/homarr-labs/homarr/commit/2c6b7a818e9d32b414b024d711a3b64533e61cb9))
|
||||
* redirect to login after credentials logout instead of crashing on current page ([#5819](https://github.com/homarr-labs/homarr/issues/5819)) ([cc24f07](https://github.com/homarr-labs/homarr/commit/cc24f070db26337a4a2d87d68c7f142ed1118584))
|
||||
* sync docs sitemap and remove stale coolify ts-expect-error ([4f5f3e1](https://github.com/homarr-labs/homarr/commit/4f5f3e14a129a94295d4b8ffb7d3702fdb4f6a74))
|
||||
* **ui:** restore pre-v9 light variant colors ([#5856](https://github.com/homarr-labs/homarr/issues/5856)) ([a755692](https://github.com/homarr-labs/homarr/commit/a755692d81b80b5ff83051a3b7261c01ac10321b))
|
||||
|
||||
## [1.63.0](https://github.com/homarr-labs/homarr/compare/v1.62.0...v1.63.0) (2026-05-29)
|
||||
|
||||
### Features
|
||||
|
||||
* **auth:** support custom token endpoint auth methods ([#5806](https://github.com/homarr-labs/homarr/issues/5806)) ([be61602](https://github.com/homarr-labs/homarr/commit/be61602576a8bec4bb7e4928d36e0854e926264d))
|
||||
* auto-open widget settings on add with all integrations pre-selected ([#5767](https://github.com/homarr-labs/homarr/issues/5767)) ([f10bb3a](https://github.com/homarr-labs/homarr/commit/f10bb3ae23fefc9779332733706aa567cc40ba48))
|
||||
* **board:** persist category collapse state in localStorage for guests ([#5714](https://github.com/homarr-labs/homarr/issues/5714)) ([66212b4](https://github.com/homarr-labs/homarr/commit/66212b4e475738e61d2ea78f3a7e72d7a610bf12)), closes [#3355](https://github.com/homarr-labs/homarr/issues/3355)
|
||||
* **manage:** unified management page layout ([#5758](https://github.com/homarr-labs/homarr/issues/5758)) ([c252b4f](https://github.com/homarr-labs/homarr/commit/c252b4f9accc4523f222354c73f687714640701f))
|
||||
* **users:** rework general settings ([#4915](https://github.com/homarr-labs/homarr/issues/4915)) ([2991777](https://github.com/homarr-labs/homarr/commit/2991777b0a0ae72522d0769a86a91250d618dbe6))
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* matine ui fixes for concistency ([#5733](https://github.com/homarr-labs/homarr/issues/5733)) ([4454e3f](https://github.com/homarr-labs/homarr/commit/4454e3fb7afa624ee2f1eaec015f2725e664ac46))
|
||||
* parse Speedtest Tracker created_at as local time ([#5751](https://github.com/homarr-labs/homarr/issues/5751)) ([b19549b](https://github.com/homarr-labs/homarr/commit/b19549b601636bcbc2fadaa270a77a9fdb48b77a))
|
||||
* prevent GitHub releases check from blocking app on API failure ([#5807](https://github.com/homarr-labs/homarr/issues/5807)) ([6cc2ac5](https://github.com/homarr-labs/homarr/commit/6cc2ac56a920563c47aaaab1b33b19a9b6d5ecee))
|
||||
* **ui:** use imported theme instead of undefined createTheme ([4a67bf0](https://github.com/homarr-labs/homarr/commit/4a67bf0ef30ff8d10b06d2d3719ccab792395669))
|
||||
|
||||
### Performance Improvements
|
||||
|
||||
* **boards:** parallelize board page data fetching ([#5736](https://github.com/homarr-labs/homarr/issues/5736)) ([8f03a38](https://github.com/homarr-labs/homarr/commit/8f03a38de5b9b385da7ffcc9a963be00710acb5e))
|
||||
|
||||
## [1.62.0](https://github.com/homarr-labs/homarr/compare/v1.61.1...v1.62.0) (2026-05-22)
|
||||
|
||||
### Features
|
||||
|
||||
* **seed:** add demo mode with pre-seeded user ([#5739](https://github.com/homarr-labs/homarr/issues/5739)) ([dade477](https://github.com/homarr-labs/homarr/commit/dade477b3226765eb614e66588ebee84c45cb688))
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **deps:** update dependency better-sqlite3 to ^12.10.0 ([#5727](https://github.com/homarr-labs/homarr/issues/5727)) ([044ad9e](https://github.com/homarr-labs/homarr/commit/044ad9edf9c1dc9b50b9591dea0b5f0cce4be01a))
|
||||
* **docker:** improve icon matching ([#5693](https://github.com/homarr-labs/homarr/issues/5693)) ([7cd30b6](https://github.com/homarr-labs/homarr/commit/7cd30b640cbf47e4678abda18f83c0924f039b1b))
|
||||
* exclude .env files from Docker build context ([#5738](https://github.com/homarr-labs/homarr/issues/5738)) ([fa73763](https://github.com/homarr-labs/homarr/commit/fa737638a812372d904207fe7af5bd7c6f53d159))
|
||||
* **tracearr:** support absolute image urls ([#5654](https://github.com/homarr-labs/homarr/issues/5654)) ([7a12721](https://github.com/homarr-labs/homarr/commit/7a1272146c597c1f9df89d74b8389f70e7cdd61a))
|
||||
|
||||
### Performance Improvements
|
||||
|
||||
* (next branch) reduce idle memory on startup ([#5637](https://github.com/homarr-labs/homarr/issues/5637)) ([5ee84f8](https://github.com/homarr-labs/homarr/commit/5ee84f8cf464c308729281cb4db572950ba85a82))
|
||||
* **boards:** remove loading overlay and show board immediately ([#5735](https://github.com/homarr-labs/homarr/issues/5735)) ([df4b57b](https://github.com/homarr-labs/homarr/commit/df4b57bd414d4402522f9210b1470d0561c37274))
|
||||
* **memory:** combine 3 node processes into one ([#5600](https://github.com/homarr-labs/homarr/issues/5600)) ([a1aa550](https://github.com/homarr-labs/homarr/commit/a1aa5505a365688b456090a882770e561479833e))
|
||||
|
||||
## [1.61.1](https://github.com/homarr-labs/homarr/compare/v1.61.0...v1.61.1) (2026-05-18)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
"@dnd-kit/modifiers": "catalog:",
|
||||
"@dnd-kit/sortable": "catalog:",
|
||||
"@dnd-kit/utilities": "catalog:",
|
||||
"@gfazioli/mantine-onboarding-tour": "catalog:",
|
||||
"@homarr/analytics": "workspace:^0.1.0",
|
||||
"@homarr/api": "workspace:^0.1.0",
|
||||
"@homarr/auth": "workspace:^0.1.0",
|
||||
|
||||
@@ -38,6 +38,7 @@ export const createBoardContentPage = <TParams extends Record<string, unknown>>(
|
||||
layout: createBoardLayout({
|
||||
headerActions: <BoardContentHeaderActions />,
|
||||
getInitialBoardAsync: getInitialBoard,
|
||||
withTour: true,
|
||||
}),
|
||||
// eslint-disable-next-line no-restricted-syntax
|
||||
page: async ({ params }: { params: Promise<TParams> }) => {
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
|
||||
import { useCallback, useEffect } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Group, Menu, ScrollArea } from "@mantine/core";
|
||||
import { OnboardingTour } from "@gfazioli/mantine-onboarding-tour";
|
||||
import { Box, Group, Menu, ScrollArea } from "@mantine/core";
|
||||
import { useHotkeys } from "@mantine/hooks";
|
||||
import {
|
||||
IconBox,
|
||||
@@ -57,9 +58,11 @@ export const BoardContentHeaderActions = () => {
|
||||
<EditModeMenu demoMode={demoMode ?? false} />
|
||||
|
||||
{!demoMode && (
|
||||
<HeaderButton href={`/boards/${board.name}/settings`}>
|
||||
<IconSettings stroke={1.5} />
|
||||
</HeaderButton>
|
||||
<OnboardingTour.Target id="board-settings">
|
||||
<HeaderButton href={`/boards/${board.name}/settings`}>
|
||||
<IconSettings stroke={1.5} />
|
||||
</HeaderButton>
|
||||
</OnboardingTour.Target>
|
||||
)}
|
||||
|
||||
<SelectBoardsMenu />
|
||||
@@ -195,9 +198,11 @@ const EditModeMenu = ({ demoMode }: { demoMode: boolean }) => {
|
||||
usePreventLeaveWithDirty(isEditMode);
|
||||
|
||||
return (
|
||||
<HeaderButton onClick={toggle} loading={isPending}>
|
||||
{isEditMode ? <IconPencilOff stroke={1.5} /> : <IconPencil stroke={1.5} />}
|
||||
</HeaderButton>
|
||||
<OnboardingTour.Target id="board-edit-mode">
|
||||
<HeaderButton onClick={toggle} loading={isPending}>
|
||||
{isEditMode ? <IconPencilOff stroke={1.5} /> : <IconPencil stroke={1.5} />}
|
||||
</HeaderButton>
|
||||
</OnboardingTour.Target>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -205,27 +210,31 @@ const SelectBoardsMenu = () => {
|
||||
const { data: boards = [] } = clientApi.board.getAllBoards.useQuery();
|
||||
|
||||
return (
|
||||
<Menu position="bottom-end">
|
||||
<Menu.Target>
|
||||
<HeaderButton w="auto" px={4}>
|
||||
<IconReplace stroke={1.5} />
|
||||
</HeaderButton>
|
||||
</Menu.Target>
|
||||
<Menu.Dropdown style={{ transform: "translate(-7px, 0)" }}>
|
||||
<ScrollArea.Autosize mah={300}>
|
||||
{boards.map((board) => (
|
||||
<Menu.Item
|
||||
key={board.id}
|
||||
component={Link}
|
||||
href={`/boards/${board.name}`}
|
||||
leftSection={<IconLayoutBoard size={20} />}
|
||||
>
|
||||
{board.name}
|
||||
</Menu.Item>
|
||||
))}
|
||||
</ScrollArea.Autosize>
|
||||
</Menu.Dropdown>
|
||||
</Menu>
|
||||
<OnboardingTour.Target id="board-switcher">
|
||||
<Box>
|
||||
<Menu position="bottom-end">
|
||||
<Menu.Target>
|
||||
<HeaderButton w="auto" px={4}>
|
||||
<IconReplace stroke={1.5} />
|
||||
</HeaderButton>
|
||||
</Menu.Target>
|
||||
<Menu.Dropdown style={{ transform: "translate(-7px, 0)" }}>
|
||||
<ScrollArea.Autosize mah={300}>
|
||||
{boards.map((board) => (
|
||||
<Menu.Item
|
||||
key={board.id}
|
||||
component={Link}
|
||||
href={`/boards/${board.name}`}
|
||||
leftSection={<IconLayoutBoard size={20} />}
|
||||
>
|
||||
{board.name}
|
||||
</Menu.Item>
|
||||
))}
|
||||
</ScrollArea.Autosize>
|
||||
</Menu.Dropdown>
|
||||
</Menu>
|
||||
</Box>
|
||||
</OnboardingTour.Target>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -266,7 +275,7 @@ const usePreventLeaveWithDirty = (isDirty: boolean) => {
|
||||
};
|
||||
|
||||
const handleBeforeUnload = (event: BeforeUnloadEvent) => {
|
||||
if (env.NODE_ENV === "development") return; // Allow to reload in development
|
||||
if (env.NODE_ENV === "development") return;
|
||||
|
||||
event.preventDefault();
|
||||
event.returnValue = true;
|
||||
|
||||
@@ -11,6 +11,7 @@ import { createLogger } from "@homarr/core/infrastructure/logs";
|
||||
import { MainHeader } from "~/components/layout/header";
|
||||
import { BoardLogoWithTitle } from "~/components/layout/logo/board-logo";
|
||||
import { ClientShell } from "~/components/layout/shell";
|
||||
import { BoardTourProvider } from "~/components/onboarding/board-tour";
|
||||
import { getCurrentColorSchemeAsync } from "~/theme/color-scheme";
|
||||
import type { Board } from "./_types";
|
||||
import type { Params } from "./(content)/_creator";
|
||||
@@ -20,14 +21,21 @@ import { BoardMantineProvider } from "./(content)/_theme";
|
||||
|
||||
const logger = createLogger({ module: "createBoardLayout" });
|
||||
|
||||
const BoardTourWrapper = ({ hasSession, children }: PropsWithChildren<{ hasSession: boolean }>) => {
|
||||
if (!hasSession) return <>{children}</>;
|
||||
return <BoardTourProvider>{children}</BoardTourProvider>;
|
||||
};
|
||||
|
||||
interface CreateBoardLayoutProps<TParams extends Params> {
|
||||
headerActions: JSX.Element;
|
||||
getInitialBoardAsync: (params: TParams) => Promise<Board>;
|
||||
withTour?: boolean;
|
||||
}
|
||||
|
||||
export const createBoardLayout = <TParams extends Params>({
|
||||
headerActions,
|
||||
getInitialBoardAsync: getInitialBoard,
|
||||
withTour = false,
|
||||
}: CreateBoardLayoutProps<TParams>) => {
|
||||
const Layout = async ({
|
||||
params,
|
||||
@@ -61,14 +69,16 @@ export const createBoardLayout = <TParams extends Params>({
|
||||
<EditModeProvider>
|
||||
<BoardMantineProvider defaultColorScheme={colorScheme}>
|
||||
<CustomCss />
|
||||
<ClientShell hasNavigation={false}>
|
||||
<MainHeader
|
||||
logo={<BoardLogoWithTitle size="md" hideTitleOnMobile />}
|
||||
actions={headerActions}
|
||||
hasNavigation={false}
|
||||
/>
|
||||
<AppShellMain>{children}</AppShellMain>
|
||||
</ClientShell>
|
||||
<BoardTourWrapper hasSession={withTour && !!session}>
|
||||
<ClientShell hasNavigation={false}>
|
||||
<MainHeader
|
||||
logo={<BoardLogoWithTitle size="md" hideTitleOnMobile />}
|
||||
actions={headerActions}
|
||||
hasNavigation={false}
|
||||
/>
|
||||
<AppShellMain>{children}</AppShellMain>
|
||||
</ClientShell>
|
||||
</BoardTourWrapper>
|
||||
</BoardMantineProvider>
|
||||
</EditModeProvider>
|
||||
</BoardReadyProvider>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { Metadata, Viewport } from "next";
|
||||
import { Inter } from "next/font/google";
|
||||
|
||||
import "@gfazioli/mantine-onboarding-tour/styles.css";
|
||||
import "@homarr/notifications/styles.css";
|
||||
import "@homarr/spotlight/styles.css";
|
||||
import "@homarr/ui/styles.css";
|
||||
|
||||
@@ -11,6 +11,7 @@ import type { inferSearchParamsFromSchema } from "@homarr/common/types";
|
||||
import { getI18n, getScopedI18n } from "@homarr/translation/server";
|
||||
import { Link, SearchInput, TablePagination } from "@homarr/ui";
|
||||
|
||||
import { TourTarget } from "~/components/layout/header/tour-target";
|
||||
import { ManagePageLayout } from "~/components/manage/manage-page-layout";
|
||||
import { MobileAffixButton } from "~/components/manage/mobile-affix-button";
|
||||
import { NoResults } from "~/components/no-results";
|
||||
@@ -45,9 +46,11 @@ export default async function AppsPage(props: AppsPageProps) {
|
||||
title={t("page.list.title")}
|
||||
primaryAction={
|
||||
canCreate ? (
|
||||
<MobileAffixButton component={Link} href="/manage/apps/new">
|
||||
{t("page.create.title")}
|
||||
</MobileAffixButton>
|
||||
<TourTarget id="manage-apps-create">
|
||||
<MobileAffixButton component={Link} href="/manage/apps/new">
|
||||
{t("page.create.title")}
|
||||
</MobileAffixButton>
|
||||
</TourTarget>
|
||||
) : undefined
|
||||
}
|
||||
toolbar={<SearchInput placeholder={`${t("search")}...`} defaultValue={searchParams.search} flexExpand />}
|
||||
@@ -56,11 +59,13 @@ export default async function AppsPage(props: AppsPageProps) {
|
||||
>
|
||||
{apps.length === 0 && <AppNoResults />}
|
||||
{apps.length > 0 && (
|
||||
<Stack gap="sm">
|
||||
{apps.map((app) => (
|
||||
<AppCard key={app.id} app={app} />
|
||||
))}
|
||||
</Stack>
|
||||
<TourTarget id="manage-apps-list">
|
||||
<Stack gap="sm">
|
||||
{apps.map((app) => (
|
||||
<AppCard key={app.id} app={app} />
|
||||
))}
|
||||
</Stack>
|
||||
</TourTarget>
|
||||
)}
|
||||
</ManagePageLayout>
|
||||
);
|
||||
|
||||
@@ -28,6 +28,7 @@ import { getScopedI18n } from "@homarr/translation/server";
|
||||
import { Link, UserAvatar } from "@homarr/ui";
|
||||
|
||||
import { getBoardPermissionsAsync } from "~/components/board/permissions/server";
|
||||
import { TourTarget } from "~/components/layout/header/tour-target";
|
||||
import { ManagePageLayout } from "~/components/manage/manage-page-layout";
|
||||
import { NoResults } from "~/components/no-results";
|
||||
import { BoardCardMenuDropdown } from "./_components/board-card-menu-dropdown";
|
||||
@@ -42,18 +43,26 @@ export default async function ManageBoardsPage() {
|
||||
return (
|
||||
<ManagePageLayout
|
||||
title={t("title")}
|
||||
primaryAction={canCreateBoards ? <CreateBoardButton /> : undefined}
|
||||
primaryAction={
|
||||
canCreateBoards ? (
|
||||
<TourTarget id="manage-boards-create">
|
||||
<CreateBoardButton />
|
||||
</TourTarget>
|
||||
) : undefined
|
||||
}
|
||||
floatingPrimaryAction={canCreateBoards}
|
||||
>
|
||||
{boards.length === 0 && <NoResults icon={IconLayoutDashboard} title={t("noResults.title")} />}
|
||||
{boards.length > 0 && (
|
||||
<Grid>
|
||||
{boards.map((board) => (
|
||||
<GridCol span={{ base: 12, md: 6 }} key={board.id}>
|
||||
<BoardCard board={board} />
|
||||
</GridCol>
|
||||
))}
|
||||
</Grid>
|
||||
<TourTarget id="manage-boards-list">
|
||||
<Grid>
|
||||
{boards.map((board) => (
|
||||
<GridCol span={{ base: 12, md: 6 }} key={board.id}>
|
||||
<BoardCard board={board} />
|
||||
</GridCol>
|
||||
))}
|
||||
</Grid>
|
||||
</TourTarget>
|
||||
)}
|
||||
</ManagePageLayout>
|
||||
);
|
||||
|
||||
+2
@@ -8,6 +8,7 @@ import {
|
||||
IconPasswordUser,
|
||||
IconPlug,
|
||||
IconServer,
|
||||
IconTag,
|
||||
IconUser,
|
||||
} from "@tabler/icons-react";
|
||||
|
||||
@@ -28,4 +29,5 @@ export const integrationSecretIcons = {
|
||||
githubAppId: IconCode,
|
||||
githubInstallationId: IconPlug,
|
||||
privateKey: IconKey,
|
||||
slug: IconTag,
|
||||
} satisfies Record<IntegrationSecretKind, TablerIcon>;
|
||||
@@ -29,6 +29,7 @@ import { getIntegrationName } from "@homarr/definitions";
|
||||
import { getScopedI18n } from "@homarr/translation/server";
|
||||
import { CountBadge, IntegrationAvatar, Link } from "@homarr/ui";
|
||||
|
||||
import { TourTarget } from "~/components/layout/header/tour-target";
|
||||
import { ManagePageLayout } from "~/components/manage/manage-page-layout";
|
||||
import { MobileAffixButton } from "~/components/manage/mobile-affix-button";
|
||||
import { NoResults } from "~/components/no-results";
|
||||
@@ -60,14 +61,18 @@ export default async function IntegrationsPage(props: IntegrationsPageProps) {
|
||||
title={t("page.list.title")}
|
||||
primaryAction={
|
||||
canCreateIntegrations ? (
|
||||
<MobileAffixButton component={Link} href="/manage/integrations/new">
|
||||
{t("action.create")}
|
||||
</MobileAffixButton>
|
||||
<TourTarget id="manage-integrations-create">
|
||||
<MobileAffixButton component={Link} href="/manage/integrations/new">
|
||||
{t("action.create")}
|
||||
</MobileAffixButton>
|
||||
</TourTarget>
|
||||
) : undefined
|
||||
}
|
||||
floatingPrimaryAction={canCreateIntegrations}
|
||||
>
|
||||
<IntegrationList integrations={integrations} activeTab={searchParams.tab} />
|
||||
<TourTarget id="manage-integrations-list">
|
||||
<IntegrationList integrations={integrations} activeTab={searchParams.tab} />
|
||||
</TourTarget>
|
||||
</ManagePageLayout>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -36,6 +36,7 @@ import { homarrLogoPath } from "~/components/layout/logo/homarr-logo";
|
||||
import type { NavigationLink } from "~/components/layout/navigation";
|
||||
import { MainNavigation } from "~/components/layout/navigation";
|
||||
import { ClientShell } from "~/components/layout/shell";
|
||||
import { ManageTourProvider } from "~/components/onboarding/manage-tour";
|
||||
|
||||
export default async function ManageLayout({ children }: PropsWithChildren) {
|
||||
const t = await getScopedI18n("management.navbar");
|
||||
@@ -45,11 +46,13 @@ export default async function ManageLayout({ children }: PropsWithChildren) {
|
||||
label: t("items.home"),
|
||||
icon: IconHomeFilled,
|
||||
href: "/manage",
|
||||
"data-onboarding-tour-id": "manage-welcome",
|
||||
},
|
||||
{
|
||||
icon: IconLayoutDashboardFilled,
|
||||
href: "/manage/boards",
|
||||
label: t("items.boards"),
|
||||
"data-onboarding-tour-id": "manage-boards",
|
||||
},
|
||||
{
|
||||
icon: IconBox,
|
||||
@@ -59,12 +62,14 @@ export default async function ManageLayout({ children }: PropsWithChildren) {
|
||||
iconProps: {
|
||||
strokeWidth: 2.5,
|
||||
},
|
||||
"data-onboarding-tour-id": "manage-apps",
|
||||
},
|
||||
{
|
||||
icon: IconAffiliateFilled,
|
||||
href: "/manage/integrations",
|
||||
label: t("items.integrations"),
|
||||
hidden: !session,
|
||||
"data-onboarding-tour-id": "manage-integrations",
|
||||
},
|
||||
{
|
||||
icon: IconSearch,
|
||||
@@ -74,17 +79,20 @@ export default async function ManageLayout({ children }: PropsWithChildren) {
|
||||
iconProps: {
|
||||
strokeWidth: 2.5,
|
||||
},
|
||||
"data-onboarding-tour-id": "manage-search-engines",
|
||||
},
|
||||
{
|
||||
icon: IconPhotoFilled,
|
||||
href: "/manage/medias",
|
||||
label: t("items.medias"),
|
||||
hidden: !session,
|
||||
"data-onboarding-tour-id": "manage-medias",
|
||||
},
|
||||
{
|
||||
icon: IconUserFilled,
|
||||
label: t("items.users.label"),
|
||||
hidden: !session?.user.permissions.includes("admin"),
|
||||
"data-onboarding-tour-id": "manage-users",
|
||||
items: [
|
||||
{
|
||||
label: t("items.users.items.manage"),
|
||||
@@ -153,6 +161,7 @@ export default async function ManageLayout({ children }: PropsWithChildren) {
|
||||
href: "/manage/settings",
|
||||
icon: IconSettingsFilled,
|
||||
hidden: !session?.user.permissions.includes("admin"),
|
||||
"data-onboarding-tour-id": "manage-settings",
|
||||
},
|
||||
{
|
||||
label: t("items.help.label"),
|
||||
@@ -191,11 +200,17 @@ export default async function ManageLayout({ children }: PropsWithChildren) {
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
const isAdmin = session?.user.permissions.includes("admin") ?? false;
|
||||
|
||||
const shell = (
|
||||
<ClientShell hasNavigation>
|
||||
<MainHeader></MainHeader>
|
||||
<MainNavigation links={navigationLinks}></MainNavigation>
|
||||
<AppShellMain>{children}</AppShellMain>
|
||||
</ClientShell>
|
||||
);
|
||||
|
||||
if (!session) return shell;
|
||||
|
||||
return <ManageTourProvider isAdmin={isAdmin}>{shell}</ManageTourProvider>;
|
||||
}
|
||||
@@ -1,23 +1,26 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import type { MantineColor } from "@mantine/core";
|
||||
import { Avatar, Badge, Box, Button, Group, Text } from "@mantine/core";
|
||||
import { ActionIcon, Avatar, Badge, Box, Button, Group, Menu, Text, Tooltip } from "@mantine/core";
|
||||
import {
|
||||
IconCategoryPlus,
|
||||
IconDots,
|
||||
IconFileText,
|
||||
IconPlayerPlay,
|
||||
IconPlayerStop,
|
||||
IconRefresh,
|
||||
IconRotateClockwise,
|
||||
IconTrash,
|
||||
} from "@tabler/icons-react";
|
||||
import type { MRT_ColumnDef } from "mantine-react-table";
|
||||
import type { MRT_ColumnDef, MRT_Row } from "mantine-react-table";
|
||||
import { MantineReactTable } from "mantine-react-table";
|
||||
|
||||
import type { RouterOutputs } from "@homarr/api";
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { useTimeAgo } from "@homarr/common";
|
||||
import { humanFileSize, useTimeAgo } from "@homarr/common";
|
||||
import type { ContainerState } from "@homarr/docker";
|
||||
import { containerStateColorMap } from "@homarr/docker/shared";
|
||||
import { containerStateColorMap, cpuUsageColor, memoryUsageColor, safeValue } from "@homarr/docker/shared";
|
||||
import { useModalAction } from "@homarr/modals";
|
||||
import { AddDockerAppToHomarr } from "@homarr/modals-collection";
|
||||
import { showErrorNotification, showSuccessNotification } from "@homarr/notifications";
|
||||
@@ -27,25 +30,30 @@ import type { TablerIcon } from "@homarr/ui";
|
||||
import { OverflowBadge } from "@homarr/ui";
|
||||
import { useTranslatedMantineReactTable } from "@homarr/ui/hooks";
|
||||
|
||||
const createColumns = (
|
||||
t: TranslationFunction,
|
||||
): MRT_ColumnDef<RouterOutputs["docker"]["getContainers"]["containers"][number]>[] => [
|
||||
type DockerContainer = RouterOutputs["docker"]["getContainers"]["containers"][number];
|
||||
|
||||
const createContainerLogsPath = (container: Pick<DockerContainer, "id" | "name">) =>
|
||||
`/manage/tools/docker/logs/${container.id}?name=${encodeURIComponent(container.name)}`;
|
||||
|
||||
const createColumns = (t: TranslationFunction): MRT_ColumnDef<DockerContainer>[] => [
|
||||
{
|
||||
accessorKey: "name",
|
||||
header: t("docker.field.name.label"),
|
||||
Cell({ renderedCellValue, row }) {
|
||||
return (
|
||||
<Group gap="xs">
|
||||
<Group gap="xs" wrap="nowrap">
|
||||
<Avatar
|
||||
variant="outline"
|
||||
radius="lg"
|
||||
radius="sm"
|
||||
size="md"
|
||||
styles={{ image: { objectFit: "contain" } }}
|
||||
src={row.original.iconUrl}
|
||||
>
|
||||
{row.original.name.at(0)?.toUpperCase()}
|
||||
</Avatar>
|
||||
<Text>{renderedCellValue}</Text>
|
||||
<Text truncate="end" maw={500}>
|
||||
{renderedCellValue}
|
||||
</Text>
|
||||
</Group>
|
||||
);
|
||||
},
|
||||
@@ -76,11 +84,11 @@ const createColumns = (
|
||||
maxSize: 200,
|
||||
Cell({ renderedCellValue, cell }) {
|
||||
return (
|
||||
<Box maw={200}>
|
||||
<Text truncate="end" title={cell.row.original.image}>
|
||||
{renderedCellValue}
|
||||
</Text>
|
||||
</Box>
|
||||
<Tooltip label={cell.row.original.image} multiline maw={400}>
|
||||
<Box maw={200}>
|
||||
<Text truncate="end">{renderedCellValue}</Text>
|
||||
</Box>
|
||||
</Tooltip>
|
||||
);
|
||||
},
|
||||
},
|
||||
@@ -95,13 +103,57 @@ const createColumns = (
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "cpuUsage",
|
||||
accessorKey: "cpuUsage",
|
||||
size: 120,
|
||||
header: t("docker.field.stats.cpu.label"),
|
||||
enableHiding: true,
|
||||
sortingFn: (rowA, rowB) => {
|
||||
const cpuUsageA = safeValue(rowA.original.cpuUsage);
|
||||
const cpuUsageB = safeValue(rowB.original.cpuUsage);
|
||||
|
||||
return cpuUsageA - cpuUsageB;
|
||||
},
|
||||
Cell({ row }) {
|
||||
const cpuUsage = safeValue(row.original.cpuUsage);
|
||||
|
||||
return (
|
||||
<Text size="sm" c={cpuUsageColor(cpuUsage, row.original.state)}>
|
||||
{cpuUsage.toFixed(2)}%
|
||||
</Text>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "memoryUsage",
|
||||
accessorKey: "memoryUsage",
|
||||
size: 140,
|
||||
header: t("docker.field.stats.memory.label"),
|
||||
enableHiding: true,
|
||||
sortingFn: (rowA, rowB) => {
|
||||
const memoryUsageA = safeValue(rowA.original.memoryUsage);
|
||||
const memoryUsageB = safeValue(rowB.original.memoryUsage);
|
||||
|
||||
return memoryUsageA - memoryUsageB;
|
||||
},
|
||||
Cell({ row }) {
|
||||
const bytesUsage = safeValue(row.original.memoryUsage);
|
||||
|
||||
return (
|
||||
<Text size="sm" c={memoryUsageColor(bytesUsage, row.original.state)}>
|
||||
{humanFileSize(bytesUsage)}
|
||||
</Text>
|
||||
);
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
export function DockerTable(initialData: RouterOutputs["docker"]["getContainers"]) {
|
||||
export function DockerTable({ containers, timestamp }: RouterOutputs["docker"]["getContainers"]) {
|
||||
const t = useI18n();
|
||||
const tDocker = useScopedI18n("docker");
|
||||
const { data } = clientApi.docker.getContainers.useQuery(undefined, {
|
||||
initialData,
|
||||
initialData: { containers, timestamp },
|
||||
refetchOnMount: false,
|
||||
refetchOnWindowFocus: false,
|
||||
refetchOnReconnect: false,
|
||||
@@ -131,6 +183,8 @@ export function DockerTable(initialData: RouterOutputs["docker"]["getContainers"
|
||||
enableColumnFilters: false,
|
||||
enablePagination: false,
|
||||
enableRowSelection: true,
|
||||
enableRowActions: true,
|
||||
positionActionsColumn: "last",
|
||||
positionToolbarAlertBanner: "top",
|
||||
enableTableFooter: false,
|
||||
enableBottomToolbar: false,
|
||||
@@ -141,7 +195,10 @@ export function DockerTable(initialData: RouterOutputs["docker"]["getContainers"
|
||||
autoFocus: true,
|
||||
},
|
||||
|
||||
initialState: { density: "xs", showGlobalFilter: true },
|
||||
initialState: { density: "xs", showGlobalFilter: true, columnVisibility: { cpuUsage: false, memoryUsage: false } },
|
||||
mantineTableBodyCellProps: { style: { padding: "4px 8px" } },
|
||||
mantineTableHeadCellProps: { style: { padding: "4px 8px" } },
|
||||
renderRowActions: ({ row }: { row: MRT_Row<DockerContainer> }) => <ContainerRowMenu container={row.original} />,
|
||||
renderTopToolbarCustomActions: () => (
|
||||
<Button variant="default" rightSection={<IconRefresh size="1rem" />} onClick={() => mutate()} loading={isPending}>
|
||||
{tDocker("action.refresh.label")}
|
||||
@@ -174,28 +231,104 @@ export function DockerTable(initialData: RouterOutputs["docker"]["getContainers"
|
||||
);
|
||||
}
|
||||
|
||||
const containerActions: { action: "start" | "stop" | "restart" | "remove"; icon: TablerIcon; color: MantineColor }[] = [
|
||||
{ action: "start", icon: IconPlayerPlay, color: "green" },
|
||||
{ action: "stop", icon: IconPlayerStop, color: "red" },
|
||||
{ action: "restart", icon: IconRotateClockwise, color: "orange" },
|
||||
{ action: "remove", icon: IconTrash, color: "red" },
|
||||
];
|
||||
|
||||
const ContainerRowMenu = ({ container }: { container: DockerContainer }) => {
|
||||
const t = useScopedI18n("docker.action");
|
||||
const router = useRouter();
|
||||
const utils = clientApi.useUtils();
|
||||
const { openModal } = useModalAction(AddDockerAppToHomarr);
|
||||
|
||||
const useContainerAction = (action: "start" | "stop" | "restart" | "remove") =>
|
||||
clientApi.docker[`${action}All`].useMutation({
|
||||
async onSettled() {
|
||||
await utils.docker.getContainers.invalidate();
|
||||
},
|
||||
onSuccess() {
|
||||
showSuccessNotification({
|
||||
title: t(`${action}.notification.success.title`),
|
||||
message: t(`${action}.notification.success.message`),
|
||||
});
|
||||
},
|
||||
onError() {
|
||||
showErrorNotification({
|
||||
title: t(`${action}.notification.error.title`),
|
||||
message: t(`${action}.notification.error.message`),
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
const mutations = {
|
||||
start: useContainerAction("start"),
|
||||
stop: useContainerAction("stop"),
|
||||
restart: useContainerAction("restart"),
|
||||
remove: useContainerAction("remove"),
|
||||
};
|
||||
|
||||
return (
|
||||
<Menu withinPortal position="bottom-end" shadow="sm">
|
||||
<Menu.Target>
|
||||
<ActionIcon variant="subtle" color="gray" onClick={(e) => e.stopPropagation()}>
|
||||
<IconDots size="1rem" />
|
||||
</ActionIcon>
|
||||
</Menu.Target>
|
||||
<Menu.Dropdown>
|
||||
<Menu.Item
|
||||
leftSection={<IconFileText size="1rem" />}
|
||||
onClick={() => router.push(createContainerLogsPath(container))}
|
||||
>
|
||||
{t("logs.label")}
|
||||
</Menu.Item>
|
||||
<Menu.Divider />
|
||||
{containerActions.map(({ action, icon: Icon, color }) => (
|
||||
<Menu.Item
|
||||
key={action}
|
||||
leftSection={<Icon size="1rem" />}
|
||||
color={color}
|
||||
onClick={() => mutations[action].mutate({ ids: [container.id] })}
|
||||
>
|
||||
{t(`${action}.label`)}
|
||||
</Menu.Item>
|
||||
))}
|
||||
<Menu.Divider />
|
||||
<Menu.Item
|
||||
leftSection={<IconCategoryPlus size="1rem" />}
|
||||
color="red"
|
||||
onClick={() => openModal({ selectedContainers: [container] })}
|
||||
>
|
||||
{t("addToHomarr.label")}
|
||||
</Menu.Item>
|
||||
</Menu.Dropdown>
|
||||
</Menu>
|
||||
);
|
||||
};
|
||||
|
||||
interface ContainerActionBarProps {
|
||||
selectedContainers: RouterOutputs["docker"]["getContainers"]["containers"];
|
||||
selectedContainers: DockerContainer[];
|
||||
}
|
||||
|
||||
const ContainerActionBar = ({ selectedContainers }: ContainerActionBarProps) => {
|
||||
const t = useScopedI18n("docker.action");
|
||||
const { openModal } = useModalAction(AddDockerAppToHomarr);
|
||||
const handleClick = () => {
|
||||
openModal({
|
||||
selectedContainers,
|
||||
});
|
||||
};
|
||||
|
||||
const selectedIds = selectedContainers.map((container) => container.id);
|
||||
|
||||
return (
|
||||
<Group gap="xs">
|
||||
<ContainerActionBarButton icon={IconPlayerPlay} color="green" action="start" selectedIds={selectedIds} />
|
||||
<ContainerActionBarButton icon={IconPlayerStop} color="red" action="stop" selectedIds={selectedIds} />
|
||||
<ContainerActionBarButton icon={IconRotateClockwise} color="orange" action="restart" selectedIds={selectedIds} />
|
||||
<ContainerActionBarButton icon={IconTrash} color="red" action="remove" selectedIds={selectedIds} />
|
||||
<Button leftSection={<IconCategoryPlus />} color={"red"} onClick={handleClick} variant="light">
|
||||
{containerActions.map(({ action, icon, color }) => (
|
||||
<ContainerActionBarButton key={action} icon={icon} color={color} action={action} selectedIds={selectedIds} />
|
||||
))}
|
||||
<Button
|
||||
leftSection={<IconCategoryPlus />}
|
||||
color="red"
|
||||
onClick={() => openModal({ selectedContainers })}
|
||||
variant="light"
|
||||
>
|
||||
{t("addToHomarr.label")}
|
||||
</Button>
|
||||
</Group>
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
"use client";
|
||||
|
||||
import dynamic from "next/dynamic";
|
||||
|
||||
export const ClientSideDockerLogsTerminal = dynamic(
|
||||
() => import("./terminal").then(({ DockerLogsTerminal }) => DockerLogsTerminal),
|
||||
{
|
||||
ssr: false,
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,47 @@
|
||||
import { notFound } from "next/navigation";
|
||||
import { Box, Group } from "@mantine/core";
|
||||
|
||||
import { api } from "@homarr/api/server";
|
||||
import { auth } from "@homarr/auth/next";
|
||||
import { env } from "@homarr/docker/env";
|
||||
|
||||
import "@xterm/xterm/css/xterm.css";
|
||||
|
||||
import { DynamicBreadcrumb } from "~/components/navigation/dynamic-breadcrumb";
|
||||
import { fullHeightWithoutHeaderAndFooter } from "~/constants";
|
||||
import { ClientSideDockerLogsTerminal } from "./client";
|
||||
|
||||
interface DockerContainerLogsPageProps {
|
||||
params: Promise<{ containerId: string }>;
|
||||
searchParams: Promise<{ name?: string }>;
|
||||
}
|
||||
|
||||
export default async function DockerContainerLogsPage({ params, searchParams }: DockerContainerLogsPageProps) {
|
||||
const session = await auth();
|
||||
if (!(session?.user.permissions.includes("admin") && env.ENABLE_DOCKER)) {
|
||||
notFound();
|
||||
}
|
||||
|
||||
const { containerId } = await params;
|
||||
const { name } = await searchParams;
|
||||
|
||||
try {
|
||||
await api.docker.logs({ id: containerId, tail: 1 });
|
||||
} catch {
|
||||
notFound();
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Group justify="space-between" align="center" wrap="nowrap">
|
||||
<DynamicBreadcrumb
|
||||
dynamicMappings={new Map([[containerId, name ?? containerId]])}
|
||||
nonInteractable={[containerId]}
|
||||
/>
|
||||
</Group>
|
||||
<Box style={{ borderRadius: 6 }} h={fullHeightWithoutHeaderAndFooter} p="md" bg="black">
|
||||
<ClientSideDockerLogsTerminal containerId={containerId} />
|
||||
</Box>
|
||||
</>
|
||||
);
|
||||
}
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
.outerTerminal > div {
|
||||
height: 100%;
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useRef } from "react";
|
||||
import { Box } from "@mantine/core";
|
||||
import { CanvasAddon } from "@xterm/addon-canvas";
|
||||
import { FitAddon } from "@xterm/addon-fit";
|
||||
import { Terminal } from "@xterm/xterm";
|
||||
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
|
||||
import classes from "./terminal.module.css";
|
||||
|
||||
interface DockerLogsTerminalProps {
|
||||
containerId: string;
|
||||
}
|
||||
|
||||
export const DockerLogsTerminal = ({ containerId }: DockerLogsTerminalProps) => {
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
const terminalRef = useRef<Terminal | null>(null);
|
||||
const pendingLogsRef = useRef<string[]>([]);
|
||||
const isTerminalReadyRef = useRef(false);
|
||||
|
||||
const writeToTerminal = useCallback((data: string) => {
|
||||
if (!isTerminalReadyRef.current || !terminalRef.current) {
|
||||
pendingLogsRef.current.push(data);
|
||||
return;
|
||||
}
|
||||
|
||||
terminalRef.current.write(data);
|
||||
terminalRef.current.refresh(0, terminalRef.current.rows - 1);
|
||||
}, []);
|
||||
|
||||
clientApi.docker.subscribeLogs.useSubscription(
|
||||
{ id: containerId, tail: 200 },
|
||||
{
|
||||
onData: writeToTerminal,
|
||||
onError(err) {
|
||||
writeToTerminal(`\r\n\x1b[31m${err.message}\x1b[0m`);
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!ref.current) {
|
||||
return () => undefined;
|
||||
}
|
||||
|
||||
const canvasAddon = new CanvasAddon();
|
||||
|
||||
terminalRef.current = new Terminal({
|
||||
cursorBlink: false,
|
||||
disableStdin: true,
|
||||
convertEol: true,
|
||||
fontSize: 14,
|
||||
});
|
||||
terminalRef.current.open(ref.current);
|
||||
terminalRef.current.loadAddon(canvasAddon);
|
||||
|
||||
isTerminalReadyRef.current = true;
|
||||
const terminal = terminalRef.current;
|
||||
pendingLogsRef.current.forEach((data) => terminal.write(data));
|
||||
pendingLogsRef.current = [];
|
||||
terminal.refresh(0, terminal.rows - 1);
|
||||
|
||||
setTimeout(() => {
|
||||
const fitAddon = new FitAddon();
|
||||
terminalRef.current?.loadAddon(fitAddon);
|
||||
fitAddon.fit();
|
||||
});
|
||||
|
||||
return () => {
|
||||
isTerminalReadyRef.current = false;
|
||||
pendingLogsRef.current = [];
|
||||
canvasAddon.dispose();
|
||||
terminalRef.current?.dispose();
|
||||
terminalRef.current = null;
|
||||
};
|
||||
}, [writeToTerminal]);
|
||||
|
||||
return <Box ref={ref} className={classes.outerTerminal} h="100%" />;
|
||||
};
|
||||
@@ -57,8 +57,9 @@ export const TerminalComponent = () => {
|
||||
});
|
||||
|
||||
return () => {
|
||||
terminalRef.current?.dispose();
|
||||
canvasAddon.dispose();
|
||||
terminalRef.current?.dispose();
|
||||
terminalRef.current = null;
|
||||
};
|
||||
}, []);
|
||||
|
||||
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
"use client";
|
||||
|
||||
import { Badge, Button, Group, Stack, Text } from "@mantine/core";
|
||||
import { IconRefresh } from "@tabler/icons-react";
|
||||
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { showSuccessNotification } from "@homarr/notifications";
|
||||
import { useScopedI18n } from "@homarr/translation/client";
|
||||
|
||||
export const ResetTours = () => {
|
||||
const t = useScopedI18n("management.page.user.setting.general.item.onboardingTours");
|
||||
const utils = clientApi.useUtils();
|
||||
const { data: tourStatus } = clientApi.user.getTourStatus.useQuery();
|
||||
const { mutate: resetTours, isPending } = clientApi.user.resetTours.useMutation({
|
||||
onSuccess() {
|
||||
showSuccessNotification({
|
||||
title: t("resetSuccess.title"),
|
||||
message: t("resetSuccess.message"),
|
||||
});
|
||||
void utils.user.getTourStatus.invalidate();
|
||||
},
|
||||
});
|
||||
|
||||
const tours = [
|
||||
{ key: "management" as const, completed: tourStatus?.completedManageTour ?? false },
|
||||
{ key: "dashboard" as const, completed: tourStatus?.completedBoardTour ?? false },
|
||||
];
|
||||
|
||||
return (
|
||||
<Stack gap="xs">
|
||||
<Group gap="xs">
|
||||
{tours.map(({ key, completed }) => (
|
||||
<Badge key={key} color={completed ? "green" : "gray"} variant="light">
|
||||
{t(`name.${key}`)}: {completed ? t("status.completed") : t("status.notStarted")}
|
||||
</Badge>
|
||||
))}
|
||||
</Group>
|
||||
<Text size="sm" c="dimmed">
|
||||
{t("description")}
|
||||
</Text>
|
||||
<Button
|
||||
leftSection={<IconRefresh size={16} />}
|
||||
variant="light"
|
||||
size="sm"
|
||||
w="fit-content"
|
||||
onClick={() => resetTours()}
|
||||
loading={isPending}
|
||||
>
|
||||
{t("reset")}
|
||||
</Button>
|
||||
</Stack>
|
||||
);
|
||||
};
|
||||
@@ -13,6 +13,7 @@ import { canAccessUserEditPage } from "../access";
|
||||
import { DeleteUserButton } from "./_components/_delete-user-button";
|
||||
import { UserGeneralSettingsForm } from "./_components/_general-settings-form";
|
||||
import { UserProfileAvatarForm } from "./_components/_profile-avatar-form";
|
||||
import { ResetTours } from "./_components/_reset-tours";
|
||||
|
||||
interface Props {
|
||||
params: Promise<{
|
||||
@@ -87,6 +88,13 @@ export default async function EditUserPage(props: Props) {
|
||||
</Box>
|
||||
</Group>
|
||||
|
||||
{session?.user.id === user.id && (
|
||||
<Stack mb="lg">
|
||||
<Title order={2}>{tGeneral("item.onboardingTours.title")}</Title>
|
||||
<ResetTours />
|
||||
</Stack>
|
||||
)}
|
||||
|
||||
<DangerZoneRoot>
|
||||
<DangerZoneItem
|
||||
label={t("user.action.delete.label")}
|
||||
|
||||
@@ -10,7 +10,7 @@ import { UserAvatar } from "@homarr/ui";
|
||||
|
||||
import { ManageContainer } from "~/components/manage/manage-container";
|
||||
import { DynamicBreadcrumb } from "~/components/navigation/dynamic-breadcrumb";
|
||||
import { catchTrpcNotFound } from "~/errors/trpc-catch-error";
|
||||
import { catchTrpcNotFound, catchTrpcUnauthorized } from "~/errors/trpc-catch-error";
|
||||
import { NavigationLink } from "../groups/[id]/_navigation";
|
||||
import { canAccessUserEditPage } from "./access";
|
||||
|
||||
@@ -26,7 +26,7 @@ export default async function Layout(props: PropsWithChildren<LayoutProps>) {
|
||||
const session = await auth();
|
||||
const t = await getI18n();
|
||||
const tUser = await getScopedI18n("management.page.user");
|
||||
const user = await api.user.getById({ userId: params.userId }).catch(catchTrpcNotFound);
|
||||
const user = await api.user.getById({ userId: params.userId }).catch(catchTrpcNotFound).catch(catchTrpcUnauthorized);
|
||||
|
||||
if (!canAccessUserEditPage(session, user.id)) {
|
||||
notFound();
|
||||
|
||||
@@ -5,7 +5,7 @@ import { api } from "@homarr/api/server";
|
||||
import { auth } from "@homarr/auth/next";
|
||||
import { getScopedI18n } from "@homarr/translation/server";
|
||||
|
||||
import { catchTrpcNotFound } from "~/errors/trpc-catch-error";
|
||||
import { catchTrpcNotFound, catchTrpcUnauthorized } from "~/errors/trpc-catch-error";
|
||||
import { canAccessUserEditPage } from "../access";
|
||||
import { ChangePasswordForm } from "./_components/_change-password-form";
|
||||
|
||||
@@ -23,7 +23,8 @@ export default async function UserSecurityPage(props: Props) {
|
||||
.getById({
|
||||
userId: params.userId,
|
||||
})
|
||||
.catch(catchTrpcNotFound);
|
||||
.catch(catchTrpcNotFound)
|
||||
.catch(catchTrpcUnauthorized);
|
||||
|
||||
if (!canAccessUserEditPage(session, user.id)) {
|
||||
notFound();
|
||||
|
||||
@@ -6,6 +6,7 @@ import { isProviderEnabled } from "@homarr/auth/server";
|
||||
import { getScopedI18n } from "@homarr/translation/server";
|
||||
import { Link } from "@homarr/ui";
|
||||
|
||||
import { TourTarget } from "~/components/layout/header/tour-target";
|
||||
import { ManagePageLayout } from "~/components/manage/manage-page-layout";
|
||||
import { MobileAffixButton } from "~/components/manage/mobile-affix-button";
|
||||
import { createMetaTitle } from "~/metadata";
|
||||
@@ -38,14 +39,18 @@ export default async function UsersPage() {
|
||||
title={t("list.title")}
|
||||
primaryAction={
|
||||
credentialsProviderEnabled ? (
|
||||
<MobileAffixButton component={Link} href="/manage/users/create">
|
||||
{t("create.title")}
|
||||
</MobileAffixButton>
|
||||
<TourTarget id="manage-users-create">
|
||||
<MobileAffixButton component={Link} href="/manage/users/create">
|
||||
{t("create.title")}
|
||||
</MobileAffixButton>
|
||||
</TourTarget>
|
||||
) : undefined
|
||||
}
|
||||
floatingPrimaryAction={credentialsProviderEnabled}
|
||||
>
|
||||
<UserListComponent initialUserList={userList} />
|
||||
<TourTarget id="manage-users-list">
|
||||
<UserListComponent initialUserList={userList} />
|
||||
</TourTarget>
|
||||
</ManagePageLayout>
|
||||
);
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import { getBoardLayouts } from "@homarr/boards/context";
|
||||
import { createId } from "@homarr/common";
|
||||
import type { Modify } from "@homarr/common/types";
|
||||
import type { WidgetKind } from "@homarr/definitions";
|
||||
import { widgetDefaultSizes } from "@homarr/definitions";
|
||||
|
||||
import type { Board, EmptySection, Item, ItemLayout } from "~/app/[locale]/boards/_types";
|
||||
import { getFirstEmptyPosition } from "./empty-position";
|
||||
@@ -19,7 +20,7 @@ export const createItemCallback =
|
||||
(previous: Board): Board => {
|
||||
const firstSection = previous.sections
|
||||
.filter((section): section is EmptySection => section.kind === "empty")
|
||||
.sort((sectionA, sectionB) => sectionA.yOffset - sectionB.yOffset)
|
||||
.toSorted((sectionA, sectionB) => sectionA.yOffset - sectionB.yOffset)
|
||||
.at(0);
|
||||
|
||||
if (!firstSection) return previous;
|
||||
@@ -28,7 +29,7 @@ export const createItemCallback =
|
||||
id: id ?? createId(),
|
||||
kind,
|
||||
options,
|
||||
layouts: createItemLayouts(previous, firstSection),
|
||||
layouts: createItemLayouts(previous, firstSection, kind),
|
||||
integrationIds,
|
||||
advancedOptions: {
|
||||
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 itemSize = getWidgetItemSize(kind);
|
||||
|
||||
return layouts.map((layoutId) => {
|
||||
const boardLayout = board.layouts.find((layout) => layout.id === layoutId);
|
||||
const elements = getSectionElements(board, { sectionId: currentSection.id, layoutId });
|
||||
|
||||
const emptyPosition = boardLayout
|
||||
? getFirstEmptyPosition(elements, boardLayout.columnCount)
|
||||
? getFirstEmptyPosition(elements, boardLayout.columnCount, 9999, itemSize)
|
||||
: { xOffset: 0, yOffset: 0 };
|
||||
|
||||
if (!emptyPosition) {
|
||||
@@ -64,8 +70,8 @@ const createItemLayouts = (board: Board, currentSection: EmptySection): ItemLayo
|
||||
}
|
||||
|
||||
return {
|
||||
width: 1,
|
||||
height: 1,
|
||||
width: itemSize.width,
|
||||
height: itemSize.height,
|
||||
...emptyPosition,
|
||||
sectionId: currentSection.id,
|
||||
layoutId,
|
||||
|
||||
@@ -57,6 +57,9 @@ export const categoryTranslationKeys: Record<string, string> = {
|
||||
mediaMonitoring: "integration.category.mediaMonitoring",
|
||||
speedtest: "integration.category.speedtest",
|
||||
analytics: "integration.category.analytics",
|
||||
documents: "integration.category.documents",
|
||||
mediaLibrary: "integration.category.mediaLibrary",
|
||||
uptimeMonitoring: "integration.category.uptimeMonitoring",
|
||||
};
|
||||
|
||||
export interface IntegrationGridItem {
|
||||
|
||||
@@ -6,6 +6,7 @@ import { Link } from "@homarr/ui";
|
||||
|
||||
import { ClientBurger } from "./header/burger";
|
||||
import { DesktopSearchInput, MobileSearchButton } from "./header/search";
|
||||
import { TourTarget } from "./header/tour-target";
|
||||
import { UserButton } from "./header/user";
|
||||
import { HomarrLogoWithTitle } from "./logo/homarr-logo";
|
||||
|
||||
@@ -25,11 +26,15 @@ export const MainHeader = ({ logo, actions, hasNavigation = true }: Props) => {
|
||||
{logo ?? <HomarrLogoWithTitle size="md" />}
|
||||
</UnstyledButton>
|
||||
</Group>
|
||||
<DesktopSearchInput />
|
||||
<TourTarget id="board-search">
|
||||
<DesktopSearchInput />
|
||||
</TourTarget>
|
||||
<Group h="100%" align="center" justify="end" style={{ flex: 1 }} wrap="nowrap">
|
||||
{actions}
|
||||
<MobileSearchButton />
|
||||
<UserButton />
|
||||
<TourTarget id="board-user-menu">
|
||||
<UserButton />
|
||||
</TourTarget>
|
||||
</Group>
|
||||
</Group>
|
||||
<Spotlight />
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
"use client";
|
||||
|
||||
import type { ReactNode } from "react";
|
||||
import { OnboardingTour } from "@gfazioli/mantine-onboarding-tour";
|
||||
import { Box } from "@mantine/core";
|
||||
|
||||
export const TourTarget = ({ id, children }: { id: string; children: ReactNode }) => (
|
||||
<OnboardingTour.Target id={id}>
|
||||
<Box data-tour-target={id}>{children}</Box>
|
||||
</OnboardingTour.Target>
|
||||
);
|
||||
@@ -1,7 +1,9 @@
|
||||
"use client";
|
||||
|
||||
import type { ReactNode } from "react";
|
||||
import { useEffect, useState } from "react";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { OnboardingTour } from "@gfazioli/mantine-onboarding-tour";
|
||||
import { NavLink } from "@mantine/core";
|
||||
|
||||
import { Link } from "@homarr/ui";
|
||||
@@ -9,9 +11,28 @@ import { Link } from "@homarr/ui";
|
||||
export const CommonNavLink = (props: ClientNavigationLink) =>
|
||||
"href" in props ? <NavLinkHref {...props} /> : <NavLinkWithItems {...props} />;
|
||||
|
||||
const NavLinkHref = (props: NavigationLinkHref) => {
|
||||
const TourTarget = ({ id, children }: { id?: string; children: ReactNode }) => {
|
||||
if (!id) return <>{children}</>;
|
||||
return <OnboardingTour.Target id={id}>{children}</OnboardingTour.Target>;
|
||||
};
|
||||
|
||||
const pathMatches = (pathname: string, href: string) => pathname === href || pathname.startsWith(`${href}/`);
|
||||
|
||||
const useClientPathname = () => {
|
||||
const pathname = usePathname();
|
||||
return props.external ? (
|
||||
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 link = props.external ? (
|
||||
<NavLink component="a" label={props.label} leftSection={props.icon} href={props.href} target="_blank" />
|
||||
) : (
|
||||
<NavLink
|
||||
@@ -19,26 +40,29 @@ const NavLinkHref = (props: NavigationLinkHref) => {
|
||||
label={props.label}
|
||||
leftSection={props.icon}
|
||||
href={props.href}
|
||||
active={pathname === props.href}
|
||||
active={isClient && pathMatches(pathname, props.href)}
|
||||
/>
|
||||
);
|
||||
return <TourTarget id={tourId}>{link}</TourTarget>;
|
||||
};
|
||||
|
||||
const NavLinkWithItems = (props: NavigationLinkWithItems) => {
|
||||
const pathname = usePathname();
|
||||
const isActive = props.items.some((item) => item.href === pathname);
|
||||
return (
|
||||
const { pathname, isClient } = useClientPathname();
|
||||
const isActive = isClient && props.items.some((item) => pathMatches(pathname, item.href));
|
||||
const nav = (
|
||||
<NavLink label={props.label} leftSection={props.icon} defaultOpened={isActive}>
|
||||
{props.items.map((item) => (
|
||||
<NavLinkHref key={item.label} {...item} />
|
||||
))}
|
||||
</NavLink>
|
||||
);
|
||||
return <TourTarget id={props["data-onboarding-tour-id"]}>{nav}</TourTarget>;
|
||||
};
|
||||
|
||||
interface CommonNavigationLinkProps {
|
||||
label: string;
|
||||
icon: ReactNode;
|
||||
"data-onboarding-tour-id"?: string;
|
||||
}
|
||||
|
||||
interface NavigationLinkHref extends CommonNavigationLinkProps {
|
||||
|
||||
@@ -27,7 +27,7 @@ export const MainNavigation = ({ headerSection, footerSection, links }: MainNavi
|
||||
return null;
|
||||
}
|
||||
|
||||
const { icon: TablerIcon, iconProps, ...props } = link;
|
||||
const { icon: TablerIcon, iconProps, "data-onboarding-tour-id": tourId, ...props } = link;
|
||||
const Icon =
|
||||
typeof TablerIcon === "string" ? (
|
||||
<Image src={TablerIcon} w={20} h={20} />
|
||||
@@ -38,17 +38,20 @@ export const MainNavigation = ({ headerSection, footerSection, links }: MainNavi
|
||||
if ("items" in props) {
|
||||
clientLink = {
|
||||
...props,
|
||||
"data-onboarding-tour-id": tourId,
|
||||
items: props.items
|
||||
.filter((item) => !item.hidden)
|
||||
.map((item) => {
|
||||
const { "data-onboarding-tour-id": itemTourId, ...rest } = item;
|
||||
return {
|
||||
...item,
|
||||
...rest,
|
||||
"data-onboarding-tour-id": itemTourId,
|
||||
icon: <item.icon size={20} stroke={1.5} {...iconProps} />,
|
||||
};
|
||||
}),
|
||||
} as ClientNavigationLink;
|
||||
} else {
|
||||
clientLink = props as ClientNavigationLink;
|
||||
clientLink = { ...props, "data-onboarding-tour-id": tourId } as ClientNavigationLink;
|
||||
}
|
||||
return <CommonNavLink key={index} {...clientLink} icon={Icon} />;
|
||||
})}
|
||||
@@ -63,6 +66,7 @@ interface CommonNavigationLinkProps {
|
||||
icon: TablerIcon | string;
|
||||
iconProps?: TablerIconProps;
|
||||
hidden?: boolean;
|
||||
"data-onboarding-tour-id"?: string;
|
||||
}
|
||||
|
||||
interface NavigationLinkHref extends CommonNavigationLinkProps {
|
||||
|
||||
@@ -58,19 +58,23 @@ export const DynamicBreadcrumb = ({
|
||||
}
|
||||
const href = `/${pathnameParts.slice(0, index + 1).join("/")}`;
|
||||
const translationKey = `${pathnameParts.slice(0, index + 1).join(".")}`;
|
||||
const mappedValue = dynamicMappings?.get(pathnamePart);
|
||||
|
||||
if (mappedValue) {
|
||||
if (nonInteractable?.includes(pathnamePart)) {
|
||||
return <Text key={href}>{mappedValue}</Text>;
|
||||
}
|
||||
return (
|
||||
<Anchor key={href} href={href}>
|
||||
{mappedValue}
|
||||
</Anchor>
|
||||
);
|
||||
}
|
||||
|
||||
if (nonInteractable?.includes(pathnamePart)) {
|
||||
return <Text key={href}>{t(`${translationKey}.label` as TranslationKeys)}</Text>;
|
||||
}
|
||||
|
||||
if (dynamicMappings?.has(pathnamePart)) {
|
||||
return (
|
||||
<Anchor key={href} href={href}>
|
||||
{dynamicMappings.get(pathnamePart)}
|
||||
</Anchor>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Anchor key={href} href={href}>
|
||||
{t(`${translationKey}.label` as TranslationKeys)}
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
"use client";
|
||||
|
||||
import type { PropsWithChildren } from "react";
|
||||
import { useMemo } from "react";
|
||||
import type { OnboardingTourStep } from "@gfazioli/mantine-onboarding-tour";
|
||||
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { useRequiredBoard } from "@homarr/boards/context";
|
||||
import { createDocumentationLink } from "@homarr/definitions";
|
||||
import { useScopedI18n } from "@homarr/translation/client";
|
||||
|
||||
import { useBoardPermissions } from "~/components/board/permissions/client";
|
||||
import { TourShell } from "./tour-shell";
|
||||
import { TourStepContent } from "./tour-step-content";
|
||||
|
||||
export const BoardTourProvider = ({ children }: PropsWithChildren) => {
|
||||
const t = useScopedI18n("onboardingTour.board");
|
||||
const board = useRequiredBoard();
|
||||
const { hasChangeAccess } = useBoardPermissions(board);
|
||||
const utils = clientApi.useUtils();
|
||||
const { data: tourStatus } = clientApi.user.getTourStatus.useQuery();
|
||||
const { mutate: completeTour } = clientApi.user.completeTour.useMutation({
|
||||
onSuccess() {
|
||||
void utils.user.getTourStatus.invalidate();
|
||||
},
|
||||
});
|
||||
|
||||
const started = tourStatus !== undefined && !tourStatus.completedBoardTour;
|
||||
|
||||
const handleEnd = () => {
|
||||
utils.user.getTourStatus.setData(undefined, {
|
||||
completedManageTour: tourStatus?.completedManageTour ?? false,
|
||||
completedBoardTour: true,
|
||||
});
|
||||
completeTour({ tour: "board" });
|
||||
};
|
||||
|
||||
const steps = useMemo(() => {
|
||||
const allSteps: (OnboardingTourStep & { requiresChangeAccess?: boolean })[] = [
|
||||
{
|
||||
id: "board-search",
|
||||
title: t("welcome.title"),
|
||||
content: (
|
||||
<TourStepContent
|
||||
description={t("welcome.description")}
|
||||
documentationHref={createDocumentationLink(
|
||||
"/docs/getting-started/after-the-installation",
|
||||
"#creating-your-first-board",
|
||||
)}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "board-edit-mode",
|
||||
title: t("editMode.title"),
|
||||
requiresChangeAccess: true,
|
||||
content: (
|
||||
<TourStepContent
|
||||
description={t("editMode.description")}
|
||||
documentationHref={createDocumentationLink(
|
||||
"/docs/getting-started/after-the-installation",
|
||||
"#arrange-and-organize-your-board",
|
||||
)}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "board-settings",
|
||||
title: t("settings.title"),
|
||||
requiresChangeAccess: true,
|
||||
content: (
|
||||
<TourStepContent
|
||||
description={t("settings.description")}
|
||||
documentationHref={createDocumentationLink("/docs/management/boards")}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "board-switcher",
|
||||
title: t("switcher.title"),
|
||||
content: (
|
||||
<TourStepContent
|
||||
description={t("switcher.description")}
|
||||
documentationHref={createDocumentationLink("/docs/management/boards")}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "board-user-menu",
|
||||
title: t("userMenu.title"),
|
||||
content: (
|
||||
<TourStepContent
|
||||
description={t("userMenu.description")}
|
||||
documentationHref={createDocumentationLink("/docs/management/users")}
|
||||
/>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
return allSteps.filter((step) => !step.requiresChangeAccess || hasChangeAccess) as OnboardingTourStep[];
|
||||
}, [hasChangeAccess, t]);
|
||||
|
||||
return (
|
||||
<TourShell steps={steps} started={started} onEnd={handleEnd} position={{ base: "bottom", sm: "left" }}>
|
||||
{children}
|
||||
</TourShell>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,220 @@
|
||||
"use client";
|
||||
|
||||
import type { PropsWithChildren } from "react";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { usePathname, useRouter } from "next/navigation";
|
||||
import type { OnboardingTourFocusRevealProps, OnboardingTourStep } from "@gfazioli/mantine-onboarding-tour";
|
||||
import { useMediaQuery } from "@mantine/hooks";
|
||||
import {
|
||||
IconAffiliateFilled,
|
||||
IconAppsFilled,
|
||||
IconLayoutDashboardFilled,
|
||||
IconPlus,
|
||||
IconUserFilled,
|
||||
} from "@tabler/icons-react";
|
||||
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { createDocumentationLink } from "@homarr/definitions";
|
||||
import { useScopedI18n } from "@homarr/translation/client";
|
||||
|
||||
import { TourShell } from "./tour-shell";
|
||||
import { TourStepContent } from "./tour-step-content";
|
||||
|
||||
interface ManageTourProviderProps extends PropsWithChildren {
|
||||
isAdmin: boolean;
|
||||
}
|
||||
|
||||
const stepRoutes: Record<string, string> = {
|
||||
"manage-welcome": "/manage",
|
||||
"manage-boards-list": "/manage/boards",
|
||||
"manage-boards-create": "/manage/boards",
|
||||
"manage-apps-list": "/manage/apps",
|
||||
"manage-apps-create": "/manage/apps",
|
||||
"manage-integrations-list": "/manage/integrations",
|
||||
"manage-integrations-create": "/manage/integrations",
|
||||
"manage-users-list": "/manage/users",
|
||||
"manage-users-create": "/manage/users",
|
||||
};
|
||||
|
||||
const usersStepFocusRevealProps: OnboardingTourFocusRevealProps = {
|
||||
withReveal: false,
|
||||
popoverProps: {
|
||||
position: "bottom",
|
||||
middlewares: { shift: { padding: 16 }, flip: true },
|
||||
},
|
||||
};
|
||||
|
||||
export const ManageTourProvider = ({ children, isAdmin }: ManageTourProviderProps) => {
|
||||
const t = useScopedI18n("onboardingTour.manage");
|
||||
const utils = clientApi.useUtils();
|
||||
const { data: tourStatus } = clientApi.user.getTourStatus.useQuery();
|
||||
const { mutate: completeTour } = clientApi.user.completeTour.useMutation({
|
||||
onSuccess() {
|
||||
void utils.user.getTourStatus.invalidate();
|
||||
},
|
||||
});
|
||||
const isMobile = useMediaQuery("(max-width: 48em)");
|
||||
const pathname = usePathname();
|
||||
const router = useRouter();
|
||||
|
||||
const isManageHome = /^(\/[^/]+)?\/manage\/?$/.test(pathname);
|
||||
const isManageSection = /^(\/[^/]+)?\/manage(\/.*)?$/.test(pathname);
|
||||
|
||||
const [tourActive, setTourActive] = useState(false);
|
||||
const [tourDismissed, setTourDismissed] = useState(false);
|
||||
const wasManageTourCompletedRef = useRef(tourStatus?.completedManageTour);
|
||||
|
||||
useEffect(() => {
|
||||
if (tourDismissed) return;
|
||||
if (isManageHome && tourStatus !== undefined && !tourStatus.completedManageTour && !isMobile) {
|
||||
setTourActive(true);
|
||||
}
|
||||
}, [isManageHome, tourStatus, isMobile, tourDismissed]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isManageSection) {
|
||||
setTourActive(false);
|
||||
}
|
||||
}, [isManageSection]);
|
||||
|
||||
useEffect(() => {
|
||||
const wasCompleted = wasManageTourCompletedRef.current;
|
||||
const isCompleted = tourStatus?.completedManageTour;
|
||||
if (wasCompleted === true && isCompleted === false) {
|
||||
setTourDismissed(false);
|
||||
}
|
||||
wasManageTourCompletedRef.current = isCompleted;
|
||||
}, [tourStatus?.completedManageTour]);
|
||||
|
||||
const handleEnd = useCallback(() => {
|
||||
setTourDismissed(true);
|
||||
setTourActive(false);
|
||||
utils.user.getTourStatus.setData(undefined, {
|
||||
completedManageTour: true,
|
||||
completedBoardTour: tourStatus?.completedBoardTour ?? false,
|
||||
});
|
||||
completeTour({ tour: "manage" });
|
||||
router.push("/manage");
|
||||
}, [completeTour, router, tourStatus?.completedBoardTour, utils.user.getTourStatus]);
|
||||
|
||||
const steps = useMemo(() => {
|
||||
const allSteps: (OnboardingTourStep & { adminOnly?: boolean })[] = [
|
||||
{
|
||||
id: "manage-welcome",
|
||||
title: t("welcome.title"),
|
||||
content: (
|
||||
<TourStepContent
|
||||
description={t("welcome.description")}
|
||||
documentationHref={createDocumentationLink("/docs/category/management")}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "manage-boards-list",
|
||||
title: t("boardsList.title"),
|
||||
content: (
|
||||
<TourStepContent
|
||||
description={t("boardsList.description")}
|
||||
documentationHref={createDocumentationLink("/docs/management/boards")}
|
||||
icon={<IconLayoutDashboardFilled size={18} />}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "manage-boards-create",
|
||||
title: t("boardsCreate.title"),
|
||||
content: (
|
||||
<TourStepContent
|
||||
description={t("boardsCreate.description")}
|
||||
documentationHref={createDocumentationLink("/docs/management/boards")}
|
||||
icon={<IconPlus size={18} />}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "manage-apps-list",
|
||||
title: t("appsList.title"),
|
||||
content: (
|
||||
<TourStepContent
|
||||
description={t("appsList.description")}
|
||||
documentationHref={createDocumentationLink("/docs/management/apps")}
|
||||
icon={<IconAppsFilled size={18} />}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "manage-apps-create",
|
||||
title: t("appsCreate.title"),
|
||||
content: (
|
||||
<TourStepContent
|
||||
description={t("appsCreate.description")}
|
||||
documentationHref={createDocumentationLink("/docs/management/apps")}
|
||||
icon={<IconPlus size={18} />}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "manage-integrations-list",
|
||||
title: t("integrationsList.title"),
|
||||
content: (
|
||||
<TourStepContent
|
||||
description={t("integrationsList.description")}
|
||||
documentationHref={createDocumentationLink("/docs/management/integrations")}
|
||||
icon={<IconAffiliateFilled size={18} />}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "manage-integrations-create",
|
||||
title: t("integrationsCreate.title"),
|
||||
content: (
|
||||
<TourStepContent
|
||||
description={t("integrationsCreate.description")}
|
||||
documentationHref={createDocumentationLink("/docs/management/integrations")}
|
||||
icon={<IconPlus size={18} />}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "manage-users-list",
|
||||
title: t("usersList.title"),
|
||||
adminOnly: true,
|
||||
focusRevealProps: usersStepFocusRevealProps,
|
||||
content: (
|
||||
<TourStepContent
|
||||
description={t("usersList.description")}
|
||||
documentationHref={createDocumentationLink("/docs/management/users")}
|
||||
icon={<IconUserFilled size={18} />}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "manage-users-create",
|
||||
title: t("usersCreate.title"),
|
||||
adminOnly: true,
|
||||
focusRevealProps: usersStepFocusRevealProps,
|
||||
content: (
|
||||
<TourStepContent
|
||||
description={t("usersCreate.description")}
|
||||
documentationHref={createDocumentationLink("/docs/management/users")}
|
||||
icon={<IconPlus size={18} />}
|
||||
/>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
return allSteps.filter((step) => !step.adminOnly || isAdmin) as OnboardingTourStep[];
|
||||
}, [isAdmin, t]);
|
||||
|
||||
return (
|
||||
<TourShell
|
||||
steps={steps}
|
||||
started={tourActive}
|
||||
onEnd={handleEnd}
|
||||
stepRoutes={stepRoutes}
|
||||
position={{ base: "bottom", sm: "right" }}
|
||||
>
|
||||
{children}
|
||||
</TourShell>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,197 @@
|
||||
"use client";
|
||||
|
||||
import type { PropsWithChildren } from "react";
|
||||
import { useCallback, useEffect, useRef } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import type { OnboardingTourController, OnboardingTourStep } from "@gfazioli/mantine-onboarding-tour";
|
||||
import { OnboardingTour } from "@gfazioli/mantine-onboarding-tour";
|
||||
import { Button, Center, Group, Image, Kbd, Text } from "@mantine/core";
|
||||
import type { FloatingPosition } from "@mantine/core";
|
||||
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
|
||||
import { homarrLogoPath } from "~/components/layout/logo/homarr-logo";
|
||||
|
||||
interface TourShellProps extends PropsWithChildren {
|
||||
steps: OnboardingTourStep[];
|
||||
started: boolean;
|
||||
onEnd: () => void;
|
||||
stepRoutes?: Record<string, string>;
|
||||
position?: FloatingPosition | Record<string, FloatingPosition>;
|
||||
}
|
||||
|
||||
type TourController = OnboardingTourController;
|
||||
|
||||
const stepIndexFromController = (controller: TourController) => controller.currentStepIndex ?? 0;
|
||||
|
||||
const stepAtOffset = (controller: TourController, offset: number) => {
|
||||
const index = stepIndexFromController(controller) + offset;
|
||||
return controller.tour[index];
|
||||
};
|
||||
|
||||
const pollForElement = (targetId: string, callback: () => void) => {
|
||||
const interval = setInterval(() => {
|
||||
const targetElement = document.querySelector(`[data-tour-target="${targetId}"]`);
|
||||
if (targetElement) {
|
||||
clearInterval(interval);
|
||||
callback();
|
||||
}
|
||||
}, 50);
|
||||
const timeout = setTimeout(() => clearInterval(interval), 5000);
|
||||
return () => {
|
||||
clearInterval(interval);
|
||||
clearTimeout(timeout);
|
||||
};
|
||||
};
|
||||
|
||||
const isTypingTarget = (target: EventTarget | null) => {
|
||||
if (!(target instanceof HTMLElement)) return false;
|
||||
const tag = target.tagName;
|
||||
return tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT" || target.isContentEditable;
|
||||
};
|
||||
|
||||
interface TourForwardButtonProps {
|
||||
label: string;
|
||||
onClick: () => void;
|
||||
}
|
||||
|
||||
const TourForwardButton = ({ label, onClick }: TourForwardButtonProps) => {
|
||||
return (
|
||||
<Button size="sm" variant="light" onClick={onClick} rightSection={<Kbd size="xs">↵</Kbd>}>
|
||||
{label}
|
||||
</Button>
|
||||
);
|
||||
};
|
||||
|
||||
interface TourDoneButtonProps {
|
||||
label: string;
|
||||
onClick: () => void;
|
||||
}
|
||||
|
||||
const TourDoneButton = ({ label, onClick }: TourDoneButtonProps) => {
|
||||
return (
|
||||
<Button size="sm" onClick={onClick} rightSection={<Kbd size="xs">↵</Kbd>}>
|
||||
{label}
|
||||
</Button>
|
||||
);
|
||||
};
|
||||
|
||||
export const TourShell = ({ steps, started, onEnd, stepRoutes, position, children }: TourShellProps) => {
|
||||
const t = useI18n();
|
||||
const router = useRouter();
|
||||
const forwardActionRef = useRef<(() => void) | null>(null);
|
||||
|
||||
const navigateAndAdvance = useCallback(
|
||||
(currentStepId: string | undefined, targetStepId: string | undefined, advance: () => void) => {
|
||||
if (!stepRoutes || !targetStepId) {
|
||||
advance();
|
||||
return;
|
||||
}
|
||||
|
||||
const currentRoute = currentStepId ? stepRoutes[currentStepId] : undefined;
|
||||
const targetRoute = stepRoutes[targetStepId];
|
||||
|
||||
if (targetRoute && targetRoute !== currentRoute) {
|
||||
router.push(targetRoute);
|
||||
pollForElement(targetStepId, advance);
|
||||
} else {
|
||||
advance();
|
||||
}
|
||||
},
|
||||
[router, stepRoutes],
|
||||
);
|
||||
|
||||
const bindForwardAction = useCallback((controller: TourController, action: () => void) => {
|
||||
forwardActionRef.current = action;
|
||||
return action;
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!started) {
|
||||
forwardActionRef.current = null;
|
||||
return;
|
||||
}
|
||||
|
||||
const onKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key !== "Enter" || event.shiftKey || event.ctrlKey || event.metaKey || event.altKey) return;
|
||||
if (isTypingTarget(event.target)) return;
|
||||
event.preventDefault();
|
||||
forwardActionRef.current?.();
|
||||
};
|
||||
|
||||
window.addEventListener("keydown", onKeyDown);
|
||||
return () => window.removeEventListener("keydown", onKeyDown);
|
||||
}, [started]);
|
||||
|
||||
return (
|
||||
<OnboardingTour
|
||||
tour={steps}
|
||||
started={started}
|
||||
onOnboardingTourEnd={onEnd}
|
||||
withStepper={false}
|
||||
header={(controller) => (
|
||||
<>
|
||||
<Group justify="center" gap={4} py={4}>
|
||||
<Text size="sm" fw={600}>
|
||||
{stepIndexFromController(controller) + 1}
|
||||
</Text>
|
||||
<Text size="sm" c="dimmed">
|
||||
/
|
||||
</Text>
|
||||
<Text size="sm" c="dimmed">
|
||||
{controller.tour.length}
|
||||
</Text>
|
||||
</Group>
|
||||
{stepIndexFromController(controller) === 0 && (
|
||||
<Center py="xs">
|
||||
<Image src={homarrLogoPath} alt="Homarr" w={64} h={64} fit="contain" />
|
||||
</Center>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
nextStepNavigation={(controller) => {
|
||||
const nextStep = stepAtOffset(controller, 1);
|
||||
const action = bindForwardAction(controller, () => {
|
||||
navigateAndAdvance(controller.currentStep?.id, nextStep?.id, () => controller.nextStep());
|
||||
});
|
||||
return <TourForwardButton label={t("onboardingTour.next")} onClick={action} />;
|
||||
}}
|
||||
endStepNavigation={(controller) => {
|
||||
const action = bindForwardAction(controller, () => controller.endTour());
|
||||
return <TourDoneButton label={t("onboardingTour.done")} onClick={action} />;
|
||||
}}
|
||||
prevStepNavigation={(controller) => (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="default"
|
||||
onClick={() => {
|
||||
const prevStep = stepAtOffset(controller, -1);
|
||||
navigateAndAdvance(controller.currentStep?.id, prevStep?.id, () => controller.prevStep());
|
||||
}}
|
||||
>
|
||||
{t("onboardingTour.prev")}
|
||||
</Button>
|
||||
)}
|
||||
skipNavigation={(controller) => (
|
||||
<Button size="sm" variant="subtle" color="gray" onClick={() => controller.skipTour()}>
|
||||
{t("onboardingTour.skip")}
|
||||
</Button>
|
||||
)}
|
||||
withPrevButton
|
||||
focusRevealProps={{
|
||||
disableTargetInteraction: true,
|
||||
popoverProps: {
|
||||
position: position ?? { base: "bottom", sm: "right" },
|
||||
width: 420,
|
||||
shadow: "xl",
|
||||
radius: "lg",
|
||||
middlewares: { shift: { padding: 16 }, flip: true },
|
||||
},
|
||||
}}
|
||||
cutoutPadding={12}
|
||||
cutoutRadius={12}
|
||||
>
|
||||
{children}
|
||||
</OnboardingTour>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,39 @@
|
||||
"use client";
|
||||
|
||||
import type { ReactNode } from "react";
|
||||
import { Anchor, Divider, Group, Stack, Text, ThemeIcon } from "@mantine/core";
|
||||
import { IconExternalLink } from "@tabler/icons-react";
|
||||
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
|
||||
interface TourStepContentProps {
|
||||
description: string;
|
||||
documentationHref: string;
|
||||
icon?: ReactNode;
|
||||
}
|
||||
|
||||
export const TourStepContent = ({ description, documentationHref, icon }: TourStepContentProps) => {
|
||||
const t = useI18n();
|
||||
|
||||
return (
|
||||
<Stack gap="sm">
|
||||
<Group gap="sm" wrap="nowrap" align="flex-start">
|
||||
{icon && (
|
||||
<ThemeIcon variant="light" size="lg" radius="md" mt={2}>
|
||||
{icon}
|
||||
</ThemeIcon>
|
||||
)}
|
||||
<Text size="sm" lh={1.7} style={{ flex: 1 }}>
|
||||
{description}
|
||||
</Text>
|
||||
</Group>
|
||||
<Divider />
|
||||
<Anchor href={documentationHref} target="_blank" size="xs" fw={500}>
|
||||
<Group gap={4} wrap="nowrap">
|
||||
<IconExternalLink size={14} />
|
||||
{t("onboardingTour.learnMore")}
|
||||
</Group>
|
||||
</Anchor>
|
||||
</Stack>
|
||||
);
|
||||
};
|
||||
@@ -45,7 +45,7 @@ export const UserAvatarMenu = ({ children, availableUpdatesPromise }: UserAvatar
|
||||
window.location.assign(logoutUrl);
|
||||
return;
|
||||
}
|
||||
router.refresh();
|
||||
router.push("/auth/login");
|
||||
},
|
||||
});
|
||||
}, [logoutUrl, openModal, router]);
|
||||
|
||||
+17
-10
@@ -249,13 +249,20 @@
|
||||
</a>
|
||||
</td>
|
||||
<td align="center">
|
||||
<a href="null" target="_blank" rel="noreferrer noopener">
|
||||
<img src="https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons@master/svg/peanut.svg" alt="PeaNUT" width="90" height="90" />
|
||||
<br/>
|
||||
<p align="center">PeaNUT</p>
|
||||
</a>
|
||||
</td></tr>
|
||||
<tr><td align="center">
|
||||
<a href="https://homarr.dev/docs/integrations/pi-hole" target="_blank" rel="noreferrer noopener">
|
||||
<img src="https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons@master/svg/pi-hole.svg" alt="Pi-hole" width="90" height="90" />
|
||||
<br/>
|
||||
<p align="center">Pi-hole</p>
|
||||
</a>
|
||||
</td></tr>
|
||||
<tr><td align="center">
|
||||
</td>
|
||||
<td align="center">
|
||||
<a href="https://homarr.dev/docs/integrations/plex" target="_blank" rel="noreferrer noopener">
|
||||
<img src="https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons@master/svg/plex.svg" alt="Plex" width="90" height="90" />
|
||||
<br/>
|
||||
@@ -296,15 +303,15 @@
|
||||
<br/>
|
||||
<p align="center">Radarr</p>
|
||||
</a>
|
||||
</td>
|
||||
<td align="center">
|
||||
</td></tr>
|
||||
<tr><td align="center">
|
||||
<a href="https://homarr.dev/docs/integrations/readarr" target="_blank" rel="noreferrer noopener">
|
||||
<img src="https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons@master/svg/readarr.svg" alt="Readarr" width="90" height="90" />
|
||||
<br/>
|
||||
<p align="center">Readarr</p>
|
||||
</a>
|
||||
</td></tr>
|
||||
<tr><td align="center">
|
||||
</td>
|
||||
<td align="center">
|
||||
<a href="https://homarr.dev/docs/integrations/sabnzbd" target="_blank" rel="noreferrer noopener">
|
||||
<img src="https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons@master/svg/sabnzbd.svg" alt="SABnzbd" width="90" height="90" />
|
||||
<br/>
|
||||
@@ -345,15 +352,15 @@
|
||||
<br/>
|
||||
<p align="center">Speedtest<br/>Tracker</p>
|
||||
</a>
|
||||
</td>
|
||||
<td align="center">
|
||||
</td></tr>
|
||||
<tr><td align="center">
|
||||
<a href="https://homarr.dev/docs/integrations/tdarr" target="_blank" rel="noreferrer noopener">
|
||||
<img src="https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons@master/png/tdarr.png" alt="Tdarr" width="90" height="90" />
|
||||
<br/>
|
||||
<p align="center">Tdarr</p>
|
||||
</a>
|
||||
</td></tr>
|
||||
<tr><td align="center">
|
||||
</td>
|
||||
<td align="center">
|
||||
<a href="https://homarr.dev/docs/integrations/tracearr" target="_blank" rel="noreferrer noopener">
|
||||
<img src="https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons@master/svg/tracearr.svg" alt="Tracearr" width="90" height="90" />
|
||||
<br/>
|
||||
|
||||
+5
-5
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "homarr",
|
||||
"version": "1.61.1",
|
||||
"version": "1.64.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"build": "cross-env CI=true turbo build",
|
||||
@@ -78,7 +78,7 @@
|
||||
"overrides": {
|
||||
"@babel/helpers@<7.26.10": ">=7.29.7",
|
||||
"@babel/runtime@<7.26.10": ">=7.29.7",
|
||||
"axios@>=1.0.0 <1.8.2": ">=1.16.1",
|
||||
"axios@>=1.0.0 <1.8.2": ">=1.17.0",
|
||||
"brace-expansion@>=2.0.0 <=2.0.1": ">=5.0.6",
|
||||
"brace-expansion@>=1.0.0 <=1.1.11": ">=5.0.6",
|
||||
"esbuild@<=0.24.2": ">=0.28.0",
|
||||
@@ -88,13 +88,13 @@
|
||||
"nanoid@>=4.0.0 <5.0.9": ">=5.1.11",
|
||||
"prismjs@<1.30.0": ">=1.30.0",
|
||||
"proxmox-api>undici": "7.24.6",
|
||||
"react-is": "^19.2.6",
|
||||
"rollup@>=4.0.0 <4.22.4": ">=4.60.4",
|
||||
"react-is": "^19.2.7",
|
||||
"rollup@>=4.0.0 <4.22.4": ">=4.61.0",
|
||||
"sha.js@<=2.4.11": ">=2.4.12",
|
||||
"tar-fs@>=3.0.0 <3.0.9": ">=3.1.2",
|
||||
"tar-fs@>=2.0.0 <2.1.3": ">=3.1.2",
|
||||
"tmp@<=0.2.3": ">=0.2.7",
|
||||
"vite@>=5.0.0 <=5.4.18": ">=8.0.14"
|
||||
"vite@>=5.0.0 <=5.4.18": ">=8.0.16"
|
||||
},
|
||||
"patchedDependencies": {
|
||||
"@types/node-unifi": "patches/@types__node-unifi.patch",
|
||||
|
||||
@@ -4,7 +4,11 @@ import { z } from "zod/v4";
|
||||
|
||||
import type { Container, ContainerState, Docker, Port } from "@homarr/docker";
|
||||
import { DockerSingleton } from "@homarr/docker";
|
||||
import { dockerContainersRequestHandler } from "@homarr/request-handler/docker";
|
||||
import {
|
||||
dockerContainersRequestHandler,
|
||||
getContainerLogsAsync,
|
||||
streamContainerLogsAsync,
|
||||
} from "@homarr/request-handler/docker";
|
||||
|
||||
import { dockerMiddleware } from "../../middlewares/docker";
|
||||
import { createTRPCRouter, permissionRequiredProcedure } from "../../trpc";
|
||||
@@ -104,6 +108,84 @@ export const dockerRouter = createTRPCRouter({
|
||||
const innerHandler = dockerContainersRequestHandler.handler({});
|
||||
await innerHandler.invalidateAsync();
|
||||
}),
|
||||
logs: permissionRequiredProcedure
|
||||
.requiresPermission("admin")
|
||||
.concat(dockerMiddleware())
|
||||
.input(
|
||||
z.object({
|
||||
id: z.string(),
|
||||
tail: z.number().min(1).max(1000).optional(),
|
||||
}),
|
||||
)
|
||||
.query(async ({ input }) => {
|
||||
const logs = await getContainerLogsAsync(input.id, input.tail ?? 200);
|
||||
|
||||
if (!logs) {
|
||||
throw new TRPCError({
|
||||
code: "NOT_FOUND",
|
||||
message: "Container not found",
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
logs,
|
||||
};
|
||||
}),
|
||||
subscribeLogs: permissionRequiredProcedure
|
||||
.requiresPermission("admin")
|
||||
.concat(dockerMiddleware())
|
||||
.input(
|
||||
z.object({
|
||||
id: z.string(),
|
||||
tail: z.number().min(1).max(1000).optional(),
|
||||
}),
|
||||
)
|
||||
.subscription(({ input }) => {
|
||||
return observable<string>((emit) => {
|
||||
let cleanupFn: (() => void) | undefined;
|
||||
let isSubscribed = true;
|
||||
|
||||
const initializeStreamAsync = async () => {
|
||||
try {
|
||||
cleanupFn = await streamContainerLogsAsync(
|
||||
input.id,
|
||||
input.tail ?? 200,
|
||||
(data) => {
|
||||
if (isSubscribed) {
|
||||
emit.next(data);
|
||||
}
|
||||
},
|
||||
(err) => {
|
||||
if (isSubscribed) {
|
||||
emit.error(
|
||||
new TRPCError({
|
||||
code: "INTERNAL_SERVER_ERROR",
|
||||
message: err.message,
|
||||
}),
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
} catch (err) {
|
||||
if (isSubscribed) {
|
||||
emit.error(
|
||||
new TRPCError({
|
||||
code: "NOT_FOUND",
|
||||
message: err instanceof Error ? err.message : "Container not found",
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
void initializeStreamAsync();
|
||||
|
||||
return () => {
|
||||
isSubscribed = false;
|
||||
cleanupFn?.();
|
||||
};
|
||||
});
|
||||
}),
|
||||
});
|
||||
|
||||
const getContainerOrDefaultAsync = async (instance: Docker, id: string) => {
|
||||
|
||||
@@ -13,6 +13,14 @@ import { dockerRouter } from "../../docker/docker-router";
|
||||
// Mock the auth module to return an empty session
|
||||
vi.mock("@homarr/auth", () => ({ auth: () => ({}) as Session }));
|
||||
vi.mock("@homarr/request-handler/docker", () => ({
|
||||
getContainerLogsAsync: async () => {
|
||||
await Promise.resolve();
|
||||
return "logs";
|
||||
},
|
||||
streamContainerLogsAsync: async () => {
|
||||
await Promise.resolve();
|
||||
return () => undefined;
|
||||
},
|
||||
dockerContainersRequestHandler: {
|
||||
handler: () => ({
|
||||
getCachedOrUpdatedDataAsync: async () => {
|
||||
@@ -65,6 +73,8 @@ const validInputs: {
|
||||
restartAll: { ids: ["1"] },
|
||||
removeAll: { ids: ["1"] },
|
||||
invalidate: undefined,
|
||||
logs: { id: "1", tail: 200 },
|
||||
subscribeLogs: { id: "1", tail: 200 },
|
||||
};
|
||||
|
||||
describe("All procedures should only be accessible for users with admin permission", () => {
|
||||
|
||||
@@ -32,6 +32,7 @@ import {
|
||||
import { convertIntersectionToZodObject } from "../schema-merger";
|
||||
import {
|
||||
createTRPCRouter,
|
||||
isDemoMode,
|
||||
onboardingProcedure,
|
||||
permissionRequiredProcedure,
|
||||
protectedProcedure,
|
||||
@@ -278,6 +279,8 @@ export const userRouter = createTRPCRouter({
|
||||
defaultSearchEngineId: true,
|
||||
openSearchInNewTab: true,
|
||||
ddgBangs: true,
|
||||
completedManageTour: true,
|
||||
completedBoardTour: true,
|
||||
}),
|
||||
)
|
||||
.meta({ openapi: { method: "GET", path: "/api/users/{userId}", tags: ["users"], protect: true } })
|
||||
@@ -304,6 +307,8 @@ export const userRouter = createTRPCRouter({
|
||||
defaultSearchEngineId: true,
|
||||
openSearchInNewTab: true,
|
||||
ddgBangs: true,
|
||||
completedManageTour: true,
|
||||
completedBoardTour: true,
|
||||
},
|
||||
where: eq(users.id, input.userId),
|
||||
});
|
||||
@@ -605,6 +610,46 @@ export const userRouter = createTRPCRouter({
|
||||
})
|
||||
.where(eq(users.id, input.id));
|
||||
}),
|
||||
completeTour: protectedProcedure
|
||||
.input(z.object({ tour: z.enum(["manage", "board"]) }))
|
||||
.mutation(async ({ input, ctx }) => {
|
||||
const columnByTour = {
|
||||
manage: { completedManageTour: true },
|
||||
board: { completedBoardTour: true },
|
||||
} as const;
|
||||
|
||||
await ctx.db.update(users).set(columnByTour[input.tour]).where(eq(users.id, ctx.session.user.id));
|
||||
}),
|
||||
resetTours: protectedProcedure.mutation(async ({ ctx }) => {
|
||||
await ctx.db
|
||||
.update(users)
|
||||
.set({
|
||||
completedManageTour: false,
|
||||
completedBoardTour: false,
|
||||
})
|
||||
.where(eq(users.id, ctx.session.user.id));
|
||||
}),
|
||||
getTourStatus: protectedProcedure.query(async ({ ctx }) => {
|
||||
if (isDemoMode) {
|
||||
return {
|
||||
completedManageTour: true,
|
||||
completedBoardTour: true,
|
||||
};
|
||||
}
|
||||
|
||||
const user = await ctx.db.query.users.findFirst({
|
||||
columns: {
|
||||
completedManageTour: true,
|
||||
completedBoardTour: true,
|
||||
},
|
||||
where: eq(users.id, ctx.session.user.id),
|
||||
});
|
||||
|
||||
return {
|
||||
completedManageTour: user?.completedManageTour ?? false,
|
||||
completedBoardTour: user?.completedBoardTour ?? false,
|
||||
};
|
||||
}),
|
||||
});
|
||||
|
||||
const createUserAsync = async (db: Database, input: Omit<z.infer<typeof userBaseCreateSchema>, "groupIds">) => {
|
||||
|
||||
@@ -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)),
|
||||
coolify: lazy(() => import("./coolify").then((mod) => mod.coolifyRouter)),
|
||||
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)),
|
||||
weather: lazy(() => import("./weather").then((mod) => mod.weatherRouter)),
|
||||
app: lazy(() => import("./app").then((mod) => mod.appRouter)),
|
||||
@@ -30,6 +31,8 @@ export const widgetRouter = createTRPCRouter({
|
||||
timetable: lazy(() => import("./timetable").then((mod) => mod.timetableRouter)),
|
||||
tracearr: lazy(() => import("./tracearr").then((mod) => mod.tracearrRouter)),
|
||||
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)),
|
||||
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());
|
||||
};
|
||||
});
|
||||
}),
|
||||
});
|
||||
@@ -0,0 +1,2 @@
|
||||
ALTER TABLE `user` ADD `completed_manage_tour` boolean DEFAULT false NOT NULL;--> statement-breakpoint
|
||||
ALTER TABLE `user` ADD `completed_board_tour` boolean DEFAULT false NOT NULL;
|
||||
File diff suppressed because it is too large.
Load diff
@@ -274,6 +274,13 @@
|
||||
"when": 1775400000000,
|
||||
"tag": "0038_add_user_ddg_bangs",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 39,
|
||||
"version": "5",
|
||||
"when": 1779199104477,
|
||||
"tag": "0039_add_user_onboarding_tour_status",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
ALTER TABLE "user" ADD COLUMN "completed_manage_tour" boolean DEFAULT false NOT NULL;--> statement-breakpoint
|
||||
ALTER TABLE "user" ADD COLUMN "completed_board_tour" boolean DEFAULT false NOT NULL;
|
||||
File diff suppressed because it is too large.
Load diff
@@ -36,6 +36,13 @@
|
||||
"when": 1775400000000,
|
||||
"tag": "0004_add_user_ddg_bangs",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 5,
|
||||
"version": "7",
|
||||
"when": 1779199097716,
|
||||
"tag": "0005_add_user_onboarding_tour_status",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -41,7 +41,16 @@ import {
|
||||
} from "../schema";
|
||||
import type { Integration } from "../schema";
|
||||
|
||||
const isTruthyEnv = (value: string | undefined) =>
|
||||
["1", "yes", "t", "true"].includes((value ?? "").toLowerCase());
|
||||
|
||||
export const seedDataAsync = async (db: Database) => {
|
||||
if (isTruthyEnv(process.env.UNSAFE_ENABLE_MOCK_INTEGRATION)) {
|
||||
console.warn(
|
||||
"UNSAFE_ENABLE_MOCK_INTEGRATION is enabled: mock integration is available in the UI. Disable by setting UNSAFE_ENABLE_MOCK_INTEGRATION=false.",
|
||||
);
|
||||
}
|
||||
|
||||
await seedEveryoneGroupAsync(db);
|
||||
await seedOnboardingAsync(db);
|
||||
await seedServerSettingsAsync(db);
|
||||
@@ -51,7 +60,7 @@ export const seedDataAsync = async (db: Database) => {
|
||||
await seedDefaultBoardAsync(db);
|
||||
await seedBoardWidgetsAsync(db);
|
||||
|
||||
if (["1", "yes", "t", "true"].includes((process.env.DEMO_MODE ?? "").toLowerCase())) {
|
||||
if (isTruthyEnv(process.env.DEMO_MODE)) {
|
||||
await seedDemoUserAsync(db);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
ALTER TABLE `user` ADD `completed_manage_tour` integer DEFAULT false NOT NULL;--> statement-breakpoint
|
||||
ALTER TABLE `user` ADD `completed_board_tour` integer DEFAULT false NOT NULL;
|
||||
File diff suppressed because it is too large.
Load diff
@@ -260,6 +260,13 @@
|
||||
"when": 1775400000000,
|
||||
"tag": "0036_add_user_ddg_bangs",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 37,
|
||||
"version": "6",
|
||||
"when": 1779199046805,
|
||||
"tag": "0037_add_user_onboarding_tour_status",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -80,6 +80,8 @@ export const users = mysqlTable("user", {
|
||||
colorScheme: varchar({ length: 5 }).$type<ColorScheme>().default("dark").notNull(),
|
||||
firstDayOfWeek: tinyint().$type<DayOfWeek>().default(1).notNull(), // Defaults to Monday
|
||||
pingIconsEnabled: boolean().default(false).notNull(),
|
||||
completedManageTour: boolean().default(false).notNull(),
|
||||
completedBoardTour: boolean().default(false).notNull(),
|
||||
});
|
||||
|
||||
export const accounts = mysqlTable(
|
||||
|
||||
@@ -79,6 +79,8 @@ export const users = pgTable("user", {
|
||||
colorScheme: varchar({ length: 5 }).$type<ColorScheme>().default("dark").notNull(),
|
||||
firstDayOfWeek: smallint().$type<DayOfWeek>().default(1).notNull(), // Defaults to Monday
|
||||
pingIconsEnabled: boolean().default(false).notNull(),
|
||||
completedManageTour: boolean().default(false).notNull(),
|
||||
completedBoardTour: boolean().default(false).notNull(),
|
||||
});
|
||||
|
||||
export const accounts = pgTable(
|
||||
|
||||
@@ -62,6 +62,8 @@ export const users = sqliteTable("user", {
|
||||
colorScheme: text().$type<ColorScheme>().default("dark").notNull(),
|
||||
firstDayOfWeek: int().$type<DayOfWeek>().default(1).notNull(), // Defaults to Monday
|
||||
pingIconsEnabled: int({ mode: "boolean" }).default(false).notNull(),
|
||||
completedManageTour: int({ mode: "boolean" }).default(false).notNull(),
|
||||
completedBoardTour: int({ mode: "boolean" }).default(false).notNull(),
|
||||
});
|
||||
|
||||
export const accounts = sqliteTable(
|
||||
|
||||
@@ -27,6 +27,10 @@ const integrationAliases: Partial<Record<IntegrationKind, readonly string[]>> =
|
||||
overseerr: ["overseerr"],
|
||||
dashDot: ["dashdot", "dash-dot", "dash."],
|
||||
speedtestTracker: ["speedtest-tracker"],
|
||||
uptimeKuma: ["uptime-kuma"],
|
||||
audiobookshelf: ["audiobookshelf"],
|
||||
navidrome: ["navidrome"],
|
||||
paperlessNgx: ["paperless-ngx", "paperless"],
|
||||
searchCh: ["search-ch"],
|
||||
gitHubContainerRegistry: ["ghcr"],
|
||||
linuxServerIO: ["linuxserver"],
|
||||
|
||||
@@ -157,6 +157,7 @@ export type HomarrDocumentationPath =
|
||||
| "/docs/integrations/anchor"
|
||||
| "/docs/integrations/aria2"
|
||||
| "/docs/integrations/codeberg"
|
||||
| "/docs/integrations/coolify"
|
||||
| "/docs/integrations/dash-dot"
|
||||
| "/docs/integrations/deluge"
|
||||
| "/docs/integrations/docker-hub"
|
||||
@@ -181,6 +182,7 @@ export type HomarrDocumentationPath =
|
||||
| "/docs/integrations/open-media-vault"
|
||||
| "/docs/integrations/opnsense"
|
||||
| "/docs/integrations/overseerr"
|
||||
| "/docs/integrations/peanut"
|
||||
| "/docs/integrations/pi-hole"
|
||||
| "/docs/integrations/plex"
|
||||
| "/docs/integrations/prowlarr"
|
||||
@@ -217,6 +219,7 @@ export type HomarrDocumentationPath =
|
||||
| "/docs/widgets/bookmarks"
|
||||
| "/docs/widgets/calendar"
|
||||
| "/docs/widgets/clock"
|
||||
| "/docs/widgets/coolify"
|
||||
| "/docs/widgets/dns-hole-controls"
|
||||
| "/docs/widgets/dns-hole-summary"
|
||||
| "/docs/widgets/docker-containers"
|
||||
@@ -247,6 +250,7 @@ export type HomarrDocumentationPath =
|
||||
| "/docs/widgets/timetable"
|
||||
| "/docs/widgets/tracearr"
|
||||
| "/docs/widgets/umami"
|
||||
| "/docs/widgets/ups"
|
||||
| "/docs/widgets/video"
|
||||
| "/docs/widgets/weather"
|
||||
| ""
|
||||
|
||||
@@ -17,6 +17,7 @@ export const integrationSecretKindObject = {
|
||||
privateKey: { isPublic: false, multiline: true },
|
||||
githubAppId: { isPublic: true, multiline: false },
|
||||
githubInstallationId: { isPublic: true, multiline: false },
|
||||
slug: { isPublic: true, multiline: false },
|
||||
} satisfies Record<string, { isPublic: boolean; multiline: boolean }>;
|
||||
|
||||
export const integrationSecretKinds = objectKeys(integrationSecretKindObject);
|
||||
@@ -383,7 +384,6 @@ export const integrationDefs = {
|
||||
secretKinds: [["apiKey"]],
|
||||
iconUrl: "https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons@master/svg/coolify.svg",
|
||||
category: ["healthMonitoring"],
|
||||
// @ts-expect-error - docs page will be created when integration is merged
|
||||
documentationUrl: createDocumentationLink("/docs/integrations/coolify"),
|
||||
defaultPort: 8000,
|
||||
},
|
||||
@@ -402,6 +402,14 @@ export const integrationDefs = {
|
||||
documentationUrl: createDocumentationLink("/docs/integrations/immich"),
|
||||
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: {
|
||||
name: "Tracearr",
|
||||
secretKinds: [["apiKey"]],
|
||||
@@ -418,6 +426,31 @@ export const integrationDefs = {
|
||||
documentationUrl: createDocumentationLink("/docs/integrations/speedtest-tracker"),
|
||||
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: {
|
||||
name: "Umami",
|
||||
secretKinds: [["username", "password"], ["apiKey"]],
|
||||
@@ -453,6 +486,7 @@ export const integrationDefs = {
|
||||
"notifications",
|
||||
"smartHomeServer",
|
||||
"ups",
|
||||
"uptimeMonitoring",
|
||||
],
|
||||
documentationUrl: null,
|
||||
},
|
||||
@@ -541,6 +575,9 @@ export const integrationCategories = [
|
||||
"speedtest",
|
||||
"analytics",
|
||||
"ups",
|
||||
"documents",
|
||||
"mediaLibrary",
|
||||
"uptimeMonitoring",
|
||||
] as const;
|
||||
|
||||
export type IntegrationCategory = (typeof integrationCategories)[number];
|
||||
@@ -33,8 +33,11 @@ export const widgetIntegrationSupport: Partial<Record<WidgetKind, readonly Integ
|
||||
timetable: ["searchCh"],
|
||||
"immich-serverStats": ["immich"],
|
||||
"immich-albumCarousel": ["immich"],
|
||||
paperlessNgx: ["paperlessNgx"],
|
||||
tracearr: ["tracearr"],
|
||||
speedtestTracker: ["speedtestTracker"],
|
||||
uptimeKuma: ["uptimeKuma"],
|
||||
audioStats: ["navidrome", "audiobookshelf"],
|
||||
anchorNote: ["anchor"],
|
||||
};
|
||||
|
||||
|
||||
@@ -35,9 +35,18 @@ export const widgetKinds = [
|
||||
"timetable",
|
||||
"immich-serverStats",
|
||||
"immich-albumCarousel",
|
||||
"paperlessNgx",
|
||||
"tracearr",
|
||||
"speedtestTracker",
|
||||
"uptimeKuma",
|
||||
"audioStats",
|
||||
"umami",
|
||||
"ups",
|
||||
] as const;
|
||||
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 },
|
||||
};
|
||||
@@ -11,3 +11,23 @@ export const containerStateColorMap = {
|
||||
removing: "pink",
|
||||
dead: "dark",
|
||||
} satisfies Record<ContainerState, MantineColor>;
|
||||
|
||||
export const memoryUsageColor = (number: number, state: string): MantineColor => {
|
||||
const mbUsage = number / 1024 / 1024;
|
||||
if (mbUsage === 0 && state !== "running") return "red";
|
||||
if (mbUsage < 128) return "green";
|
||||
if (mbUsage < 256) return "yellow";
|
||||
if (mbUsage < 512) return "orange";
|
||||
return "red";
|
||||
};
|
||||
|
||||
export const cpuUsageColor = (number: number, state: string): MantineColor => {
|
||||
if (number === 0 && state !== "running") return "red";
|
||||
if (number < 40) return "green";
|
||||
if (number < 60) return "yellow";
|
||||
if (number < 90) return "orange";
|
||||
return "red";
|
||||
};
|
||||
|
||||
export const safeValue = (value?: number, fallback = 0): number =>
|
||||
value !== undefined && !isNaN(value) ? value : fallback;
|
||||
@@ -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 { AnchorIntegration } from "../anchor/anchor-integration";
|
||||
import { AudiobookshelfIntegration } from "../audiobookshelf/audiobookshelf-integration";
|
||||
import { CodebergIntegration } from "../codeberg/codeberg-integration";
|
||||
import { CoolifyIntegration } from "../coolify/coolify-integration";
|
||||
import { DashDotIntegration } from "../dashdot/dashdot-integration";
|
||||
@@ -30,12 +31,14 @@ import { ReadarrIntegration } from "../media-organizer/readarr/readarr-integrati
|
||||
import { SonarrIntegration } from "../media-organizer/sonarr/sonarr-integration";
|
||||
import { TdarrIntegration } from "../media-transcoding/tdarr-integration";
|
||||
import { MockIntegration } from "../mock/mock-integration";
|
||||
import { NavidromeIntegration } from "../navidrome/navidrome-integration";
|
||||
import { NextcloudIntegration } from "../nextcloud/nextcloud.integration";
|
||||
import { NPMIntegration } from "../npm/npm-integration";
|
||||
import { NTFYIntegration } from "../ntfy/ntfy-integration";
|
||||
import { OpenMediaVaultIntegration } from "../openmediavault/openmediavault-integration";
|
||||
import { OPNsenseIntegration } from "../opnsense/opnsense-integration";
|
||||
import { OverseerrIntegration } from "../overseerr/overseerr-integration";
|
||||
import { PaperlessNgxIntegration } from "../paperless-ngx/paperless-ngx-integration";
|
||||
import { PeaNutIntegration } from "../peanut/peanut-integration";
|
||||
import { createPiHoleIntegrationAsync } from "../pi-hole/pi-hole-integration-factory";
|
||||
import { PlexIntegration } from "../plex/plex-integration";
|
||||
@@ -48,6 +51,7 @@ import { SpeedtestTrackerIntegration } from "../speedtest-tracker/speedtest-trac
|
||||
import { TracearrIntegration } from "../tracearr/tracearr-integration";
|
||||
import { TrueNasIntegration } from "../truenas/truenas-integration";
|
||||
import { UmamiIntegration } from "../umami/umami-integration";
|
||||
import { UptimeKumaIntegration } from "../uptime-kuma/uptime-kuma-integration";
|
||||
import { UnifiControllerIntegration } from "../unifi-controller/unifi-controller-integration";
|
||||
import { UnraidIntegration } from "../unraid/unraid-integration";
|
||||
import type { Integration, IntegrationInput } from "./integration";
|
||||
@@ -122,8 +126,12 @@ export const integrationCreators = {
|
||||
glances: GlancesIntegration,
|
||||
searchCh: SearchChIntegration,
|
||||
immich: ImmichIntegration,
|
||||
paperlessNgx: PaperlessNgxIntegration,
|
||||
speedtestTracker: SpeedtestTrackerIntegration,
|
||||
audiobookshelf: AudiobookshelfIntegration,
|
||||
navidrome: NavidromeIntegration,
|
||||
umami: UmamiIntegration,
|
||||
uptimeKuma: UptimeKumaIntegration,
|
||||
peaNut: PeaNutIntegration,
|
||||
} satisfies Record<IntegrationKind, IntegrationInstance | [(input: IntegrationInput) => Promise<Integration>]>;
|
||||
|
||||
|
||||
@@ -33,6 +33,9 @@ export { CoolifyIntegration } from "./coolify/coolify-integration";
|
||||
export { ImmichIntegration } from "./immich/immich-integration";
|
||||
export { TracearrIntegration } from "./tracearr/tracearr-integration";
|
||||
export { SpeedtestTrackerIntegration } from "./speedtest-tracker/speedtest-tracker-integration";
|
||||
export { AudiobookshelfIntegration } from "./audiobookshelf/audiobookshelf-integration";
|
||||
export { NavidromeIntegration } from "./navidrome/navidrome-integration";
|
||||
export { UptimeKumaIntegration } from "./uptime-kuma/uptime-kuma-integration";
|
||||
export { UmamiIntegration } from "./umami/umami-integration";
|
||||
export { PeaNutIntegration } from "./peanut/peanut-integration";
|
||||
|
||||
@@ -61,6 +64,7 @@ export type {
|
||||
export type { ReleasesRepository, ReleaseResponse } from "./interfaces/releases-providers/releases-providers-types";
|
||||
export type { Notification } from "./interfaces/notifications/notification-types";
|
||||
export type { ImmichServerStats, ImmichAlbum, ImmichAsset } from "./immich/immich-integration";
|
||||
export type { PaperlessNgxStats } from "./paperless-ngx/paperless-ngx-types";
|
||||
export type {
|
||||
AnchorNote,
|
||||
AnchorNotePermission,
|
||||
@@ -70,6 +74,9 @@ export type {
|
||||
} from "./anchor/anchor-types";
|
||||
export type { TracearrDashboardData } from "./tracearr/tracearr-types";
|
||||
export type { SpeedtestTrackerDashboardData } from "./speedtest-tracker/speedtest-tracker-types";
|
||||
export type { AudiobookshelfDashboardData } from "./audiobookshelf/audiobookshelf-types";
|
||||
export type { NavidromeDashboardData } from "./navidrome/navidrome-types";
|
||||
export type { UptimeKumaDashboardData } from "./uptime-kuma/uptime-kuma-types";
|
||||
export type { UmamiVisitorStats } from "./umami/umami-types";
|
||||
|
||||
// Schemas
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
import { ParseError, ResponseError } from "@homarr/common/server";
|
||||
import { createLogger } from "@homarr/core/infrastructure/logs";
|
||||
import { fetchWithTrustedCertificatesAsync } from "@homarr/core/infrastructure/http";
|
||||
|
||||
import type { IntegrationTestingInput } from "../base/integration";
|
||||
import { Integration } from "../base/integration";
|
||||
import { TestConnectionError } from "../base/test-connection/test-connection-error";
|
||||
import type { TestingResult } from "../base/test-connection/test-connection-service";
|
||||
import type { NavidromeDashboardData, NavidromeNowPlayingEntry, SubsonicResponseBody } from "./navidrome-types";
|
||||
import { subsonicResponseSchema } from "./navidrome-types";
|
||||
|
||||
const logger = createLogger({ module: "navidromeIntegration" });
|
||||
|
||||
const subsonicVersion = "1.16.1";
|
||||
const subsonicClient = "homarr";
|
||||
const albumListPageSize = 500;
|
||||
const maxAlbumListPages = 20;
|
||||
const emptyLibraryMessage = "Library not found or empty";
|
||||
|
||||
const subsonicAuthErrorCodes = new Set([40, 41]);
|
||||
|
||||
const asArray = <TValue>(value: TValue | TValue[] | undefined): TValue[] =>
|
||||
[value].flat().filter((item): item is TValue => item !== undefined);
|
||||
|
||||
export class NavidromeIntegration extends Integration {
|
||||
protected async testingAsync(input: IntegrationTestingInput): Promise<TestingResult> {
|
||||
const url = this.url("/rest/ping.view", this.getAuthParams());
|
||||
const response = await input.fetchAsync(url);
|
||||
|
||||
if (!response.ok) {
|
||||
return TestConnectionError.StatusResult(response);
|
||||
}
|
||||
|
||||
const parsed = subsonicResponseSchema.safeParse(await response.json());
|
||||
|
||||
if (!parsed.success) {
|
||||
return TestConnectionError.ParseResult(new ParseError("Invalid Subsonic response", { cause: parsed.error }));
|
||||
}
|
||||
|
||||
const subsonicResponse = parsed.data["subsonic-response"];
|
||||
|
||||
if (subsonicResponse.status === "failed") {
|
||||
const errorCode = subsonicResponse.error?.code;
|
||||
|
||||
if (errorCode !== undefined && subsonicAuthErrorCodes.has(errorCode)) {
|
||||
return TestConnectionError.UnauthorizedResult(401);
|
||||
}
|
||||
|
||||
return TestConnectionError.UnknownResult(new Error(subsonicResponse.error?.message ?? "Subsonic request failed"));
|
||||
}
|
||||
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
public async getDashboardDataAsync(): Promise<NavidromeDashboardData> {
|
||||
const [artistCount, libraryCounts, nowPlaying] = await Promise.all([
|
||||
this.getArtistCountAsync(),
|
||||
this.getAlbumAndSongCountsAsync(),
|
||||
this.getNowPlayingAsync(),
|
||||
]);
|
||||
|
||||
return {
|
||||
artistCount,
|
||||
albumCount: libraryCounts.albumCount,
|
||||
songCount: libraryCounts.songCount,
|
||||
nowPlaying,
|
||||
};
|
||||
}
|
||||
|
||||
private async getArtistCountAsync(): Promise<number> {
|
||||
const response = await this.subsonicRequestAsync("/rest/getArtists.view", {}, { tolerateEmptyLibrary: true });
|
||||
return asArray(response.artists?.index).reduce((count, index) => count + asArray(index.artist).length, 0);
|
||||
}
|
||||
|
||||
private async getAlbumAndSongCountsAsync(): Promise<{ albumCount: number; songCount: number }> {
|
||||
let offset = 0;
|
||||
let albumCount = 0;
|
||||
let songCount = 0;
|
||||
let page = 0;
|
||||
|
||||
while (page < maxAlbumListPages) {
|
||||
const response = await this.subsonicRequestAsync(
|
||||
"/rest/getAlbumList2.view",
|
||||
{
|
||||
type: "alphabeticalByName",
|
||||
size: albumListPageSize,
|
||||
offset,
|
||||
},
|
||||
{ tolerateEmptyLibrary: true },
|
||||
);
|
||||
const albums = asArray(response.albumList2?.album);
|
||||
|
||||
if (albums.length === 0) {
|
||||
break;
|
||||
}
|
||||
|
||||
albumCount += albums.length;
|
||||
|
||||
for (const album of albums) {
|
||||
songCount += album.songCount ?? 0;
|
||||
}
|
||||
|
||||
if (albums.length < albumListPageSize) {
|
||||
break;
|
||||
}
|
||||
|
||||
offset += albumListPageSize;
|
||||
page += 1;
|
||||
}
|
||||
|
||||
if (page >= maxAlbumListPages) {
|
||||
logger.warn("Reached Navidrome album list page limit", {
|
||||
integrationId: this.integration.id,
|
||||
maxPages: maxAlbumListPages,
|
||||
albumCount,
|
||||
});
|
||||
}
|
||||
|
||||
return { albumCount, songCount };
|
||||
}
|
||||
|
||||
private async getNowPlayingAsync(): Promise<NavidromeNowPlayingEntry[]> {
|
||||
const response = await this.subsonicRequestAsync("/rest/getNowPlaying.view", {}, { tolerateEmptyLibrary: true });
|
||||
|
||||
return asArray(response.nowPlaying?.entry).map((entry) => ({
|
||||
title: entry.title ?? "",
|
||||
artist: entry.artist ?? "",
|
||||
album: entry.album ?? "",
|
||||
username: entry.username ?? "",
|
||||
playerName: entry.playerName ?? "",
|
||||
}));
|
||||
}
|
||||
|
||||
private async subsonicRequestAsync(
|
||||
path: `/rest/${string}`,
|
||||
params: Record<string, string | number> = {},
|
||||
options: { tolerateEmptyLibrary?: boolean } = {},
|
||||
): Promise<SubsonicResponseBody> {
|
||||
const url = this.url(path, { ...this.getAuthParams(), ...params });
|
||||
const response = await fetchWithTrustedCertificatesAsync(url);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new ResponseError(response);
|
||||
}
|
||||
|
||||
const parsed = subsonicResponseSchema.parse(await response.json());
|
||||
const subsonicResponse = parsed["subsonic-response"];
|
||||
|
||||
if (subsonicResponse.status === "failed") {
|
||||
const message = subsonicResponse.error?.message ?? "Subsonic request failed";
|
||||
|
||||
if (options.tolerateEmptyLibrary && message === emptyLibraryMessage) {
|
||||
return subsonicResponse;
|
||||
}
|
||||
|
||||
throw new Error(message);
|
||||
}
|
||||
|
||||
return subsonicResponse;
|
||||
}
|
||||
|
||||
private getAuthParams(): Record<string, string> {
|
||||
return {
|
||||
u: this.getSecretValue("username"),
|
||||
p: this.getSecretValue("password"),
|
||||
v: subsonicVersion,
|
||||
c: subsonicClient,
|
||||
f: "json",
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import { z } from "zod/v4";
|
||||
|
||||
const subsonicArtistSchema = z.object({
|
||||
id: z.string(),
|
||||
name: z.string(),
|
||||
albumCount: z.number().optional(),
|
||||
});
|
||||
|
||||
const subsonicIndexSchema = z.object({
|
||||
name: z.string(),
|
||||
artist: z.union([subsonicArtistSchema, z.array(subsonicArtistSchema)]).optional(),
|
||||
});
|
||||
|
||||
const subsonicAlbumSchema = z.object({
|
||||
id: z.string(),
|
||||
name: z.string(),
|
||||
songCount: z.number().optional(),
|
||||
});
|
||||
|
||||
const subsonicNowPlayingEntrySchema = z.object({
|
||||
title: z.string().optional(),
|
||||
artist: z.string().optional(),
|
||||
album: z.string().optional(),
|
||||
username: z.string().optional(),
|
||||
playerName: z.string().optional(),
|
||||
});
|
||||
|
||||
export const subsonicResponseSchema = z.object({
|
||||
"subsonic-response": z.object({
|
||||
status: z.enum(["ok", "failed"]),
|
||||
version: z.string().optional(),
|
||||
error: z
|
||||
.object({
|
||||
code: z.number(),
|
||||
message: z.string(),
|
||||
})
|
||||
.optional(),
|
||||
artists: z
|
||||
.object({
|
||||
index: z.union([subsonicIndexSchema, z.array(subsonicIndexSchema)]).optional(),
|
||||
})
|
||||
.optional(),
|
||||
albumList2: z
|
||||
.object({
|
||||
album: z.union([subsonicAlbumSchema, z.array(subsonicAlbumSchema)]).optional(),
|
||||
})
|
||||
.optional(),
|
||||
nowPlaying: z
|
||||
.object({
|
||||
entry: z.union([subsonicNowPlayingEntrySchema, z.array(subsonicNowPlayingEntrySchema)]).optional(),
|
||||
})
|
||||
.optional(),
|
||||
}),
|
||||
});
|
||||
|
||||
export type SubsonicResponseBody = z.infer<typeof subsonicResponseSchema>["subsonic-response"];
|
||||
|
||||
export interface NavidromeNowPlayingEntry {
|
||||
title: string;
|
||||
artist: string;
|
||||
album: string;
|
||||
username: string;
|
||||
playerName: string;
|
||||
}
|
||||
|
||||
export interface NavidromeDashboardData {
|
||||
artistCount: number;
|
||||
albumCount: number;
|
||||
songCount: number;
|
||||
nowPlaying: NavidromeNowPlayingEntry[];
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
import { Response } from "undici";
|
||||
import { beforeEach, describe, expect, test, vi } from "vitest";
|
||||
|
||||
import { fetchWithTrustedCertificatesAsync } from "@homarr/core/infrastructure/http";
|
||||
|
||||
import type { IntegrationSecret } from "../../base/types";
|
||||
import { NavidromeIntegration } from "../navidrome-integration";
|
||||
|
||||
vi.mock("@homarr/core/infrastructure/http", () => ({
|
||||
fetchWithTrustedCertificatesAsync: vi.fn(),
|
||||
}));
|
||||
|
||||
const TEST_URL = "https://navidrome.example.com";
|
||||
const mockFetch = vi.mocked(fetchWithTrustedCertificatesAsync);
|
||||
|
||||
const secrets: IntegrationSecret[] = [
|
||||
{ kind: "username", value: "admin" },
|
||||
{ kind: "password", value: "secret" },
|
||||
];
|
||||
|
||||
const toUrlString = (url: unknown): string => String(url);
|
||||
|
||||
const createIntegration = () =>
|
||||
new NavidromeIntegration({
|
||||
id: "test-navidrome",
|
||||
name: "Test Navidrome",
|
||||
url: TEST_URL,
|
||||
externalUrl: null,
|
||||
decryptedSecrets: secrets,
|
||||
});
|
||||
|
||||
const subsonicOk = <T extends Record<string, unknown>>(data: T) =>
|
||||
JSON.stringify({
|
||||
"subsonic-response": { status: "ok", version: "1.16.1", ...data },
|
||||
});
|
||||
|
||||
const subsonicFailed = (message: string) =>
|
||||
JSON.stringify({
|
||||
"subsonic-response": { status: "failed", error: { code: 70, message } },
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
mockFetch.mockReset();
|
||||
});
|
||||
|
||||
describe("NavidromeIntegration.getDashboardDataAsync", () => {
|
||||
test("paginates album list and counts songs", async () => {
|
||||
const makeAlbums = (count: number, songCount: number) =>
|
||||
Array.from({ length: count }, (_, i) => ({
|
||||
id: `album-${i}`,
|
||||
name: `Album ${i}`,
|
||||
songCount,
|
||||
}));
|
||||
|
||||
mockFetch.mockImplementation((url) => {
|
||||
const urlStr = toUrlString(url);
|
||||
|
||||
if (urlStr.includes("getArtists")) {
|
||||
return Promise.resolve(
|
||||
new Response(subsonicOk({ artists: { index: [{ name: "A", artist: [{ id: "1", name: "Artist" }] }] } }), {
|
||||
status: 200,
|
||||
}),
|
||||
) as unknown as ReturnType<typeof fetchWithTrustedCertificatesAsync>;
|
||||
}
|
||||
|
||||
if (urlStr.includes("getAlbumList2")) {
|
||||
const offsetMatch = urlStr.match(/offset=(\d+)/);
|
||||
const offset = Number(offsetMatch?.[1] ?? 0);
|
||||
|
||||
if (offset === 0) {
|
||||
return Promise.resolve(
|
||||
new Response(subsonicOk({ albumList2: { album: makeAlbums(500, 10) } }), { status: 200 }),
|
||||
) as unknown as ReturnType<typeof fetchWithTrustedCertificatesAsync>;
|
||||
}
|
||||
|
||||
if (offset === 500) {
|
||||
return Promise.resolve(
|
||||
new Response(subsonicOk({ albumList2: { album: makeAlbums(200, 5) } }), { status: 200 }),
|
||||
) as unknown as ReturnType<typeof fetchWithTrustedCertificatesAsync>;
|
||||
}
|
||||
|
||||
return Promise.resolve(new Response(subsonicOk({ albumList2: {} }), { status: 200 })) as unknown as ReturnType<
|
||||
typeof fetchWithTrustedCertificatesAsync
|
||||
>;
|
||||
}
|
||||
|
||||
if (urlStr.includes("getNowPlaying")) {
|
||||
return Promise.resolve(new Response(subsonicOk({ nowPlaying: {} }), { status: 200 })) as unknown as ReturnType<
|
||||
typeof fetchWithTrustedCertificatesAsync
|
||||
>;
|
||||
}
|
||||
|
||||
return Promise.resolve(new Response(subsonicOk({}), { status: 200 })) as unknown as ReturnType<
|
||||
typeof fetchWithTrustedCertificatesAsync
|
||||
>;
|
||||
});
|
||||
|
||||
const integration = createIntegration();
|
||||
const result = await integration.getDashboardDataAsync();
|
||||
|
||||
expect(result.albumCount).toBe(700);
|
||||
expect(result.songCount).toBe(500 * 10 + 200 * 5);
|
||||
expect(result.artistCount).toBe(1);
|
||||
expect(result.nowPlaying).toEqual([]);
|
||||
});
|
||||
|
||||
test("handles empty library gracefully", async () => {
|
||||
mockFetch.mockImplementation((url) => {
|
||||
const urlStr = toUrlString(url);
|
||||
|
||||
if (urlStr.includes("getArtists")) {
|
||||
return Promise.resolve(
|
||||
new Response(subsonicFailed("Library not found or empty"), { status: 200 }),
|
||||
) as unknown as ReturnType<typeof fetchWithTrustedCertificatesAsync>;
|
||||
}
|
||||
|
||||
if (urlStr.includes("getAlbumList2")) {
|
||||
return Promise.resolve(
|
||||
new Response(subsonicFailed("Library not found or empty"), { status: 200 }),
|
||||
) as unknown as ReturnType<typeof fetchWithTrustedCertificatesAsync>;
|
||||
}
|
||||
|
||||
if (urlStr.includes("getNowPlaying")) {
|
||||
return Promise.resolve(
|
||||
new Response(subsonicFailed("Library not found or empty"), { status: 200 }),
|
||||
) as unknown as ReturnType<typeof fetchWithTrustedCertificatesAsync>;
|
||||
}
|
||||
|
||||
return Promise.resolve(new Response(subsonicOk({}), { status: 200 })) as unknown as ReturnType<
|
||||
typeof fetchWithTrustedCertificatesAsync
|
||||
>;
|
||||
});
|
||||
|
||||
const integration = createIntegration();
|
||||
const result = await integration.getDashboardDataAsync();
|
||||
|
||||
expect(result.artistCount).toBe(0);
|
||||
expect(result.albumCount).toBe(0);
|
||||
expect(result.songCount).toBe(0);
|
||||
expect(result.nowPlaying).toEqual([]);
|
||||
});
|
||||
|
||||
test("throws on non-empty-library subsonic error", async () => {
|
||||
mockFetch.mockImplementation(
|
||||
() =>
|
||||
Promise.resolve(new Response(subsonicFailed("Permission denied"), { status: 200 })) as unknown as ReturnType<
|
||||
typeof fetchWithTrustedCertificatesAsync
|
||||
>,
|
||||
);
|
||||
|
||||
const integration = createIntegration();
|
||||
await expect(integration.getDashboardDataAsync()).rejects.toThrow();
|
||||
});
|
||||
|
||||
test("now playing maps entries correctly", async () => {
|
||||
mockFetch.mockImplementation((url) => {
|
||||
const urlStr = toUrlString(url);
|
||||
|
||||
if (urlStr.includes("getNowPlaying")) {
|
||||
return Promise.resolve(
|
||||
new Response(
|
||||
subsonicOk({
|
||||
nowPlaying: {
|
||||
entry: { title: "Song", artist: "Band", album: "LP", username: "user1", playerName: "Chrome" },
|
||||
},
|
||||
}),
|
||||
{ status: 200 },
|
||||
),
|
||||
) as unknown as ReturnType<typeof fetchWithTrustedCertificatesAsync>;
|
||||
}
|
||||
|
||||
if (urlStr.includes("getArtists")) {
|
||||
return Promise.resolve(new Response(subsonicOk({ artists: {} }), { status: 200 })) as unknown as ReturnType<
|
||||
typeof fetchWithTrustedCertificatesAsync
|
||||
>;
|
||||
}
|
||||
|
||||
if (urlStr.includes("getAlbumList2")) {
|
||||
return Promise.resolve(new Response(subsonicOk({ albumList2: {} }), { status: 200 })) as unknown as ReturnType<
|
||||
typeof fetchWithTrustedCertificatesAsync
|
||||
>;
|
||||
}
|
||||
|
||||
return Promise.resolve(new Response(subsonicOk({}), { status: 200 })) as unknown as ReturnType<
|
||||
typeof fetchWithTrustedCertificatesAsync
|
||||
>;
|
||||
});
|
||||
|
||||
const integration = createIntegration();
|
||||
const result = await integration.getDashboardDataAsync();
|
||||
|
||||
expect(result.nowPlaying).toHaveLength(1);
|
||||
expect(result.nowPlaying[0]).toEqual({
|
||||
title: "Song",
|
||||
artist: "Band",
|
||||
album: "LP",
|
||||
username: "user1",
|
||||
playerName: "Chrome",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,67 @@
|
||||
import { ResponseError } from "@homarr/common/server";
|
||||
import { fetchWithTrustedCertificatesAsync } from "@homarr/core/infrastructure/http";
|
||||
|
||||
import type { IntegrationTestingInput } from "../base/integration";
|
||||
import { Integration } from "../base/integration";
|
||||
import { TestConnectionError } from "../base/test-connection/test-connection-error";
|
||||
import type { TestingResult } from "../base/test-connection/test-connection-service";
|
||||
import type { PaperlessNgxStats } from "./paperless-ngx-types";
|
||||
import { paperlessNgxPaginatedCountSchema, paperlessNgxStatisticsSchema } from "./paperless-ngx-types";
|
||||
|
||||
export class PaperlessNgxIntegration extends Integration {
|
||||
protected async testingAsync(input: IntegrationTestingInput): Promise<TestingResult> {
|
||||
const statisticsUrl = this.url("/api/statistics/");
|
||||
const statisticsResponse = await input.fetchAsync(statisticsUrl, {
|
||||
headers: this.getAuthHeaders(),
|
||||
});
|
||||
|
||||
if (!statisticsResponse.ok) {
|
||||
return TestConnectionError.StatusResult(statisticsResponse);
|
||||
}
|
||||
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
public async getStatsAsync(): Promise<PaperlessNgxStats> {
|
||||
const [statistics, tags, correspondents, documentTypes] = await Promise.all([
|
||||
this.fetchStatisticsAsync(),
|
||||
this.fetchCountAsync("/api/tags/"),
|
||||
this.fetchCountAsync("/api/correspondents/"),
|
||||
this.fetchCountAsync("/api/document_types/"),
|
||||
]);
|
||||
|
||||
return {
|
||||
documentsTotal: statistics.documents_total,
|
||||
documentsInbox: statistics.documents_inbox,
|
||||
correspondentsCount: correspondents,
|
||||
tagsCount: tags,
|
||||
documentTypesCount: documentTypes,
|
||||
};
|
||||
}
|
||||
|
||||
private async fetchAuthenticatedAsync(path: `/${string}`) {
|
||||
const response = await fetchWithTrustedCertificatesAsync(this.url(path), {
|
||||
headers: this.getAuthHeaders(),
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new ResponseError(response);
|
||||
}
|
||||
return response;
|
||||
}
|
||||
|
||||
private async fetchStatisticsAsync() {
|
||||
const response = await this.fetchAuthenticatedAsync("/api/statistics/");
|
||||
return paperlessNgxStatisticsSchema.parse(await response.json());
|
||||
}
|
||||
|
||||
private async fetchCountAsync(path: `/${string}`) {
|
||||
const response = await this.fetchAuthenticatedAsync(path);
|
||||
return paperlessNgxPaginatedCountSchema.parse(await response.json()).count;
|
||||
}
|
||||
|
||||
private getAuthHeaders(): Record<string, string> {
|
||||
return {
|
||||
Authorization: `Token ${this.getSecretValue("apiKey")}`,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { z } from "zod/v4";
|
||||
|
||||
export const paperlessNgxStatisticsSchema = z.object({
|
||||
documents_total: z.number(),
|
||||
documents_inbox: z
|
||||
.number()
|
||||
.nullable()
|
||||
.transform((value) => value ?? 0),
|
||||
});
|
||||
|
||||
export const paperlessNgxPaginatedCountSchema = z.object({
|
||||
count: z.number(),
|
||||
});
|
||||
|
||||
export interface PaperlessNgxStats {
|
||||
documentsTotal: number;
|
||||
documentsInbox: number;
|
||||
correspondentsCount: number;
|
||||
tagsCount: number;
|
||||
documentTypesCount: number;
|
||||
}
|
||||
@@ -17,4 +17,8 @@ export * from "./anchor/anchor-types";
|
||||
export * from "./interfaces/timetable/timetable-types";
|
||||
export * from "./tracearr/tracearr-types";
|
||||
export * from "./speedtest-tracker/speedtest-tracker-types";
|
||||
export * from "./uptime-kuma/uptime-kuma-types";
|
||||
export * from "./audiobookshelf/audiobookshelf-types";
|
||||
export * from "./navidrome/navidrome-types";
|
||||
export * from "./paperless-ngx/paperless-ngx-types";
|
||||
export * from "./umami/umami-types";
|
||||
@@ -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,53 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
import { createDockerLogStreamProcessor, decodeDockerLogs } from "./docker-log-decode";
|
||||
|
||||
const encodeDockerLogFrame = (streamType: number, message: string) => {
|
||||
const payload = Buffer.from(message, "utf-8");
|
||||
const header = Buffer.alloc(8);
|
||||
header.writeUInt8(streamType, 0);
|
||||
header.writeUInt32BE(payload.length, 4);
|
||||
return Buffer.concat([header, payload]);
|
||||
};
|
||||
|
||||
describe("decodeDockerLogs", () => {
|
||||
test("decodes multiplexed docker log frames", () => {
|
||||
const logs = Buffer.concat([encodeDockerLogFrame(1, "hello "), encodeDockerLogFrame(2, "world")]);
|
||||
|
||||
expect(decodeDockerLogs(logs)).toBe("hello world");
|
||||
});
|
||||
|
||||
test("returns plain text logs unchanged", () => {
|
||||
expect(decodeDockerLogs("plain text log")).toBe("plain text log");
|
||||
});
|
||||
|
||||
test("falls back to raw buffer text for non-multiplexed output", () => {
|
||||
expect(decodeDockerLogs(Buffer.from("raw docker output", "utf-8"))).toBe("raw docker output");
|
||||
});
|
||||
});
|
||||
|
||||
describe("createDockerLogStreamProcessor", () => {
|
||||
test("emits decoded chunks from a stream", () => {
|
||||
const messages: string[] = [];
|
||||
const processChunk = createDockerLogStreamProcessor(
|
||||
(data) => messages.push(data),
|
||||
() => undefined,
|
||||
1024,
|
||||
);
|
||||
|
||||
const chunk = encodeDockerLogFrame(1, "streamed log");
|
||||
expect(processChunk(chunk)).toBe(true);
|
||||
expect(messages).toEqual(["streamed log"]);
|
||||
});
|
||||
|
||||
test("returns false when message size exceeds limit", () => {
|
||||
const processChunk = createDockerLogStreamProcessor(
|
||||
() => undefined,
|
||||
() => undefined,
|
||||
4,
|
||||
);
|
||||
|
||||
const chunk = encodeDockerLogFrame(1, "this message is too long");
|
||||
expect(processChunk(chunk)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,89 @@
|
||||
const DOCKER_STREAM_HEADER_SIZE = 8;
|
||||
const DOCKER_STREAM_TYPES = new Set([1, 2]);
|
||||
|
||||
export const decodeDockerLogs = (logs: Buffer | string) => {
|
||||
if (typeof logs === "string") {
|
||||
return logs;
|
||||
}
|
||||
|
||||
if (logs.length === 0) {
|
||||
return "";
|
||||
}
|
||||
|
||||
let cursor = 0;
|
||||
const parts: string[] = [];
|
||||
|
||||
while (cursor < logs.length) {
|
||||
if (cursor + DOCKER_STREAM_HEADER_SIZE > logs.length) {
|
||||
break;
|
||||
}
|
||||
|
||||
const streamType = logs.readUInt8(cursor);
|
||||
if (!DOCKER_STREAM_TYPES.has(streamType)) {
|
||||
return logs.toString("utf-8");
|
||||
}
|
||||
|
||||
const length = logs.readUInt32BE(cursor + 4);
|
||||
const start = cursor + DOCKER_STREAM_HEADER_SIZE;
|
||||
const end = start + length;
|
||||
if (end > logs.length) {
|
||||
break;
|
||||
}
|
||||
|
||||
parts.push(logs.subarray(start, end).toString("utf-8"));
|
||||
cursor = end;
|
||||
}
|
||||
|
||||
const decoded = parts.join("");
|
||||
if (decoded.length === 0) {
|
||||
return logs.toString("utf-8");
|
||||
}
|
||||
|
||||
return decoded;
|
||||
};
|
||||
|
||||
export const createDockerLogStreamProcessor = (
|
||||
onData: (data: string) => void,
|
||||
onError: (err: Error) => void,
|
||||
maxMessageSize: number,
|
||||
) => {
|
||||
let buffer = Buffer.alloc(0);
|
||||
|
||||
const processChunk = (chunk: Buffer) => {
|
||||
buffer = Buffer.concat([buffer, chunk]);
|
||||
|
||||
while (buffer.length > 0) {
|
||||
if (buffer.length < DOCKER_STREAM_HEADER_SIZE) {
|
||||
break;
|
||||
}
|
||||
|
||||
const streamType = buffer.readUInt8(0);
|
||||
if (!DOCKER_STREAM_TYPES.has(streamType)) {
|
||||
onData(buffer.toString("utf-8"));
|
||||
buffer = Buffer.alloc(0);
|
||||
break;
|
||||
}
|
||||
|
||||
const length = buffer.readUInt32BE(4);
|
||||
if (length > maxMessageSize) {
|
||||
onError(
|
||||
new Error(`Docker log message size (${length} bytes) exceeds maximum allowed (${maxMessageSize} bytes)`),
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
const fullMessageSize = DOCKER_STREAM_HEADER_SIZE + length;
|
||||
if (buffer.length < fullMessageSize) {
|
||||
break;
|
||||
}
|
||||
|
||||
const payload = buffer.subarray(DOCKER_STREAM_HEADER_SIZE, fullMessageSize);
|
||||
onData(payload.toString("utf-8"));
|
||||
buffer = buffer.subarray(fullMessageSize);
|
||||
}
|
||||
|
||||
return true;
|
||||
};
|
||||
|
||||
return processChunk;
|
||||
};
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { Readable } from "node:stream";
|
||||
import dayjs from "dayjs";
|
||||
import type { ContainerInfo, ContainerStats } from "dockerode";
|
||||
import type { Container, ContainerInfo, ContainerStats } from "dockerode";
|
||||
import type Dockerode from "dockerode";
|
||||
|
||||
import { bestMatch } from "@homarr/common";
|
||||
@@ -11,6 +12,7 @@ import { extractContainerImageName } from "@homarr/definitions";
|
||||
import type { ContainerState, Port } from "@homarr/docker";
|
||||
import { dockerLabels, DockerSingleton } from "@homarr/docker";
|
||||
|
||||
import { createDockerLogStreamProcessor, decodeDockerLogs } from "./docker-log-decode";
|
||||
import { createCachedWidgetRequestHandler } from "./lib/cached-widget-request-handler";
|
||||
|
||||
const logger = createLogger({ module: "dockerRequestHandler" });
|
||||
@@ -183,6 +185,84 @@ export const dockerContainersRequestHandler = createCachedWidgetRequestHandler({
|
||||
|
||||
const extractImage = (container: ContainerInfo) => extractContainerImageName(container.Image);
|
||||
|
||||
const findContainerByIdAsync = async (id: string) => {
|
||||
const dockerInstances = DockerSingleton.getInstances();
|
||||
const containers = await Promise.all(
|
||||
dockerInstances.map(async ({ instance }) => {
|
||||
const container = instance.getContainer(id);
|
||||
|
||||
return await new Promise<Container | null>((resolve) => {
|
||||
container.inspect((err, data) => {
|
||||
if (err || !data) {
|
||||
resolve(null);
|
||||
} else {
|
||||
resolve(container);
|
||||
}
|
||||
});
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
return containers.find((container) => container) ?? null;
|
||||
};
|
||||
|
||||
export const getContainerLogsAsync = async (id: string, tail = 200) => {
|
||||
const container = await findContainerByIdAsync(id);
|
||||
if (!container) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const rawLogs = await container.logs({
|
||||
tail,
|
||||
stdout: true,
|
||||
stderr: true,
|
||||
follow: false,
|
||||
});
|
||||
|
||||
return decodeDockerLogs(rawLogs);
|
||||
};
|
||||
|
||||
export const streamContainerLogsAsync = async (
|
||||
id: string,
|
||||
tail: number,
|
||||
onData: (data: string) => void,
|
||||
onError: (err: Error) => void,
|
||||
) => {
|
||||
const container = await findContainerByIdAsync(id);
|
||||
if (!container) {
|
||||
onError(new Error("Container not found"));
|
||||
return () => undefined;
|
||||
}
|
||||
|
||||
const stream = (await container.logs({
|
||||
tail,
|
||||
stdout: true,
|
||||
stderr: true,
|
||||
follow: true,
|
||||
})) as Readable;
|
||||
|
||||
const MAX_MESSAGE_SIZE = 1024 * 1024;
|
||||
const processChunk = createDockerLogStreamProcessor(onData, onError, MAX_MESSAGE_SIZE);
|
||||
|
||||
const handleChunk = (chunk: Buffer) => {
|
||||
const shouldContinue = processChunk(chunk);
|
||||
if (!shouldContinue) {
|
||||
stream.removeListener("data", handleChunk);
|
||||
stream.removeListener("error", onError);
|
||||
stream.destroy();
|
||||
}
|
||||
};
|
||||
|
||||
stream.on("data", handleChunk);
|
||||
stream.on("error", onError);
|
||||
|
||||
return () => {
|
||||
stream.removeListener("data", handleChunk);
|
||||
stream.removeListener("error", onError);
|
||||
stream.destroy();
|
||||
};
|
||||
};
|
||||
|
||||
async function getContainersWithStatsAsync() {
|
||||
const dockerInstances = DockerSingleton.getInstances();
|
||||
const results = await Promise.allSettled(
|
||||
@@ -275,8 +355,6 @@ export function calculateMemoryUsage(stats: ContainerStats): number {
|
||||
return 0;
|
||||
}
|
||||
|
||||
// memory usage by default includes cache, which should not be shown as it is also not shown with docker stats command
|
||||
// See https://docs.docker.com/reference/cli/docker/container/stats/ how it is / was calculated
|
||||
return (
|
||||
stats.memory_stats.usage -
|
||||
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
|
||||
|
||||
@@ -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",
|
||||
"timetable": "Timetable",
|
||||
"photoService": "Photos",
|
||||
"documents": "Documents",
|
||||
"notes": "Notes",
|
||||
"mediaMonitoring": "Monitoring",
|
||||
"speedtest": "Speed Test",
|
||||
"analytics": "Analytics"
|
||||
"analytics": "Analytics",
|
||||
"mediaLibrary": "Media Library",
|
||||
"uptimeMonitoring": "Uptime Monitoring"
|
||||
},
|
||||
"testConnection": {
|
||||
"action": {
|
||||
@@ -1084,6 +1087,10 @@
|
||||
"privateKey": {
|
||||
"label": "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",
|
||||
"interact": "Interact with integrations",
|
||||
"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": {
|
||||
@@ -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": {
|
||||
"name": "Immich Server Stats",
|
||||
"description": "Information about your Immich instance",
|
||||
@@ -3037,6 +3113,113 @@
|
||||
"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": {
|
||||
"name": "System resources",
|
||||
"description": "CPU, Memory, Disk and other hardware usage of your system",
|
||||
@@ -3611,7 +3794,24 @@
|
||||
},
|
||||
"search": "Search",
|
||||
"firstDayOfWeek": "First day of the week",
|
||||
"accessibility": "Accessibility"
|
||||
"accessibility": "Accessibility",
|
||||
"onboardingTours": {
|
||||
"title": "Onboarding Tours",
|
||||
"description": "Reset the onboarding tours to see them again on your next visit to the management area or dashboard.",
|
||||
"reset": "Reset onboarding tours",
|
||||
"resetSuccess": {
|
||||
"title": "Tours reset",
|
||||
"message": "Onboarding tours will show again on your next visit"
|
||||
},
|
||||
"status": {
|
||||
"completed": "Completed",
|
||||
"notStarted": "Not started"
|
||||
},
|
||||
"name": {
|
||||
"management": "Management",
|
||||
"dashboard": "Dashboard"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"security": {
|
||||
@@ -4106,6 +4306,12 @@
|
||||
},
|
||||
"action": {
|
||||
"title": "Actions",
|
||||
"logs": {
|
||||
"label": "View logs",
|
||||
"page": {
|
||||
"title": "{name} logs"
|
||||
}
|
||||
},
|
||||
"start": {
|
||||
"label": "Start",
|
||||
"notification": {
|
||||
@@ -4518,7 +4724,10 @@
|
||||
"label": "Tasks"
|
||||
},
|
||||
"docker": {
|
||||
"label": "Docker"
|
||||
"label": "Docker",
|
||||
"logs": {
|
||||
"label": "Logs"
|
||||
}
|
||||
},
|
||||
"kubernetes": {
|
||||
"label": "Kubernetes",
|
||||
@@ -5192,5 +5401,72 @@
|
||||
"error": "Error"
|
||||
}
|
||||
}
|
||||
},
|
||||
"onboardingTour": {
|
||||
"learnMore": "Read the docs",
|
||||
"next": "Next",
|
||||
"prev": "Back",
|
||||
"done": "Done",
|
||||
"skip": "Skip tour",
|
||||
"manage": {
|
||||
"welcome": {
|
||||
"title": "Welcome to Homarr!",
|
||||
"description": "This is your control center. From here you manage boards, apps, integrations, users, and server settings. Let's take a tour of each section."
|
||||
},
|
||||
"boardsList": {
|
||||
"title": "Your Boards",
|
||||
"description": "Here are all your dashboards. Each board has its own layout, background, and access settings. You can see who created each one and whether it's public or private."
|
||||
},
|
||||
"boardsCreate": {
|
||||
"title": "Create a Board",
|
||||
"description": "Click here to create a new dashboard or import one from a previous Homarr installation. Each board gets its own URL you can share."
|
||||
},
|
||||
"appsList": {
|
||||
"title": "Your Apps",
|
||||
"description": "These are all the apps you've added — links to your self-hosted services. Each app has an icon, optional health check, and a status badge on the dashboard."
|
||||
},
|
||||
"appsCreate": {
|
||||
"title": "Add an App",
|
||||
"description": "Register a new service here. Give it a name, URL, and icon — it will appear as a tile on your boards with live status monitoring."
|
||||
},
|
||||
"integrationsList": {
|
||||
"title": "Your Integrations",
|
||||
"description": "These are the services connected to Homarr — Sonarr, Radarr, Plex, Jellyfin, and 50+ more. All credentials are encrypted at rest."
|
||||
},
|
||||
"integrationsCreate": {
|
||||
"title": "Add an Integration",
|
||||
"description": "Connect a new service here. Pick the type, enter the URL and API key — Homarr validates the connection before saving."
|
||||
},
|
||||
"usersList": {
|
||||
"title": "Your Users",
|
||||
"description": "See everyone who has access. Organize users into groups and control who can view or edit each board."
|
||||
},
|
||||
"usersCreate": {
|
||||
"title": "Create a User",
|
||||
"description": "Add a new user account here. You can also use invite links for easy onboarding. That's the tour — you're all set!"
|
||||
}
|
||||
},
|
||||
"board": {
|
||||
"welcome": {
|
||||
"title": "This is your board",
|
||||
"description": "A drag-and-drop dashboard where you arrange apps and widgets. Press Ctrl+K anytime to search for apps, boards, and actions."
|
||||
},
|
||||
"editMode": {
|
||||
"title": "Edit Mode",
|
||||
"description": "Click here to enter edit mode. You can then add widgets, apps, and sections — drag to reposition, resize with the corner handle. Click again to save your changes."
|
||||
},
|
||||
"settings": {
|
||||
"title": "Board Settings",
|
||||
"description": "Change this board's name, columns, background, colors, and who can access it. Each board can be public or private."
|
||||
},
|
||||
"switcher": {
|
||||
"title": "Switch Boards",
|
||||
"description": "Jump between boards. Create separate dashboards for different purposes — media, networking, per-user, or anything you like."
|
||||
},
|
||||
"userMenu": {
|
||||
"title": "Your Profile",
|
||||
"description": "Change your color scheme, language, home board, and preferences. You can also jump to the management area from here."
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
@import "@mantine/core/styles.css";
|
||||
@import "@mantine/charts/styles.css";
|
||||
@import "@mantine/dates/styles.css";
|
||||
@import "@gfazioli/mantine-onboarding-tour/styles.css";
|
||||
@import "mantine-react-table/styles.css";
|
||||
@@ -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;
|
||||
supportedIntegrations?: IntegrationKind[];
|
||||
integrationsRequired?: boolean;
|
||||
maxIntegrations?: number;
|
||||
createOptions: (
|
||||
settings: Pick<SettingsContextProps, "enableStatusByDefault" | "forceDisableStatus">,
|
||||
) => WidgetOptionsRecord;
|
||||
|
||||
@@ -11,7 +11,7 @@ import type { RouterOutputs } from "@homarr/api";
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { humanFileSize, useTimeAgo } from "@homarr/common";
|
||||
import type { ContainerState } from "@homarr/docker";
|
||||
import { containerStateColorMap } from "@homarr/docker/shared";
|
||||
import { containerStateColorMap, cpuUsageColor, memoryUsageColor, safeValue } from "@homarr/docker/shared";
|
||||
import { showErrorNotification, showSuccessNotification } from "@homarr/notifications";
|
||||
import { useScopedI18n } from "@homarr/translation/client";
|
||||
import { useTranslatedMantineReactTable } from "@homarr/ui/hooks";
|
||||
@@ -28,25 +28,6 @@ const ContainerStateBadge = ({ state }: { state: ContainerState }) => {
|
||||
);
|
||||
};
|
||||
|
||||
const memoryUsageColor = (number: number, state: string) => {
|
||||
const mbUsage = number / 1024 / 1024;
|
||||
if (mbUsage === 0 && state !== "running") return "red";
|
||||
if (mbUsage < 128) return "green";
|
||||
if (mbUsage < 256) return "yellow";
|
||||
if (mbUsage < 512) return "orange";
|
||||
return "red";
|
||||
};
|
||||
|
||||
const cpuUsageColor = (number: number, state: string) => {
|
||||
if (number === 0 && state !== "running") return "red";
|
||||
if (number < 40) return "green";
|
||||
if (number < 60) return "yellow";
|
||||
if (number < 90) return "orange";
|
||||
return "red";
|
||||
};
|
||||
|
||||
const safeValue = (value?: number, fallback = 0) => (value !== undefined && !isNaN(value) ? value : fallback);
|
||||
|
||||
const actionIconIconStyle: IconProps["style"] = {
|
||||
height: "var(--ai-icon-size)",
|
||||
width: "var(--ai-icon-size)",
|
||||
|
||||
@@ -8,6 +8,7 @@ import type { IntegrationKind, WidgetKind } from "@homarr/definitions";
|
||||
import type { SettingsContextProps } from "@homarr/settings/creator";
|
||||
|
||||
import * as anchorNote from "./anchor-note";
|
||||
import * as audioStats from "./audio-stats";
|
||||
import * as app from "./app";
|
||||
import * as bookmarks from "./bookmarks";
|
||||
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 networkControllerSummary from "./network-controller/summary";
|
||||
import * as notebook from "./notebook";
|
||||
import * as paperlessNgx from "./paperless-ngx";
|
||||
import * as notifications from "./notifications";
|
||||
import type { WidgetOptionDefinition } from "./options";
|
||||
import * as releases from "./releases";
|
||||
@@ -41,6 +43,7 @@ import * as rssFeed from "./rssFeed";
|
||||
import * as smartHomeEntityState from "./smart-home/entity-state";
|
||||
import * as smartHomeExecuteAutomation from "./smart-home/execute-automation";
|
||||
import * as speedtestTracker from "./speedtest-tracker";
|
||||
import * as uptimeKuma from "./uptime-kuma";
|
||||
import * as stockPrice from "./stocks";
|
||||
import * as systemDisks from "./system-disks";
|
||||
import * as systemResources from "./system-resources";
|
||||
@@ -91,8 +94,11 @@ export const widgetImports = {
|
||||
timetable,
|
||||
"immich-serverStats": immichServerStats,
|
||||
"immich-albumCarousel": immichAlbumCarousel,
|
||||
paperlessNgx,
|
||||
tracearr,
|
||||
speedtestTracker,
|
||||
uptimeKuma,
|
||||
audioStats,
|
||||
umami,
|
||||
ups,
|
||||
} satisfies WidgetImportRecord;
|
||||
|
||||
@@ -117,6 +117,10 @@ export const WidgetEditModal = createModal<ModalProps<WidgetKind>>(({ actions, i
|
||||
<WidgetIntegrationSelect
|
||||
label={t("item.edit.field.integrations.label")}
|
||||
data={innerProps.integrationData}
|
||||
canSelectMultiple={
|
||||
((widgetImports[innerProps.kind].definition as { maxIntegrations?: number }).maxIntegrations ?? Infinity) >
|
||||
1
|
||||
}
|
||||
{...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;
|
||||
}
|
||||
Loaded 100 of 106 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user