Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
525eda3cbb | ||
|
|
d0709a684c | ||
|
|
cf075040e8 |
No files matched your search
@@ -1,22 +1,39 @@
|
|||||||
import { createAsyncStoragePersister } from "@tanstack/query-async-storage-persister";
|
import { createAsyncStoragePersister } from "@tanstack/query-async-storage-persister";
|
||||||
|
import { TRPCClientError } from "@trpc/client";
|
||||||
import superjson from "superjson";
|
import superjson from "superjson";
|
||||||
|
|
||||||
import { fetchApi } from "@homarr/api/client";
|
import { fetchApi } from "@homarr/api/client";
|
||||||
import { getActiveQueryCacheBoardId, queryCacheStoragePrefix } from "@homarr/api/query-cache";
|
import { getActiveQueryCacheBoardId, queryCacheStoragePrefix } from "@homarr/api/query-cache";
|
||||||
|
|
||||||
|
// Set once the server rejects a persist mutation as read-only (demo mode),
|
||||||
|
// so we stop retrying a mutation that can never succeed.
|
||||||
|
let persistDisabled = false;
|
||||||
|
|
||||||
|
const isReadOnlyError = (error: unknown) => error instanceof TRPCClientError && error.data?.code === "FORBIDDEN";
|
||||||
|
|
||||||
const queryCacheStorage = {
|
const queryCacheStorage = {
|
||||||
getItem: (_key: string) => null as string | null,
|
getItem: (_key: string) => null as string | null,
|
||||||
async setItem(_key: string, value: string) {
|
async setItem(_key: string, value: string) {
|
||||||
|
if (persistDisabled) return;
|
||||||
const boardId = getActiveQueryCacheBoardId();
|
const boardId = getActiveQueryCacheBoardId();
|
||||||
if (!boardId) return;
|
if (!boardId) return;
|
||||||
await fetchApi.queryCache.setItem.mutate({ boardId, value }).catch((error) => {
|
await fetchApi.queryCache.setItem.mutate({ boardId, value }).catch((error) => {
|
||||||
|
if (isReadOnlyError(error)) {
|
||||||
|
persistDisabled = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
console.warn("[query-cache] persist failed", error);
|
console.warn("[query-cache] persist failed", error);
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
async removeItem(_key: string) {
|
async removeItem(_key: string) {
|
||||||
|
if (persistDisabled) return;
|
||||||
const boardId = getActiveQueryCacheBoardId();
|
const boardId = getActiveQueryCacheBoardId();
|
||||||
if (!boardId) return;
|
if (!boardId) return;
|
||||||
await fetchApi.queryCache.removeItem.mutate({ boardId }).catch((error) => {
|
await fetchApi.queryCache.removeItem.mutate({ boardId }).catch((error) => {
|
||||||
|
if (isReadOnlyError(error)) {
|
||||||
|
persistDisabled = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
console.warn("[query-cache] remove failed", error);
|
console.warn("[query-cache] remove failed", error);
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import "~/styles/gridstack.scss";
|
|||||||
|
|
||||||
import { dehydrate, HydrationBoundary } from "@tanstack/react-query";
|
import { dehydrate, HydrationBoundary } from "@tanstack/react-query";
|
||||||
import type { PersistedClient } from "@tanstack/react-query-persist-client";
|
import type { PersistedClient } from "@tanstack/react-query-persist-client";
|
||||||
|
import SuperJSON from "superjson";
|
||||||
import { getQueryClient } from "@homarr/api/server";
|
import { getQueryClient } from "@homarr/api/server";
|
||||||
import { IntegrationProvider } from "@homarr/auth/client";
|
import { IntegrationProvider } from "@homarr/auth/client";
|
||||||
import { auth } from "@homarr/auth/next";
|
import { auth } from "@homarr/auth/next";
|
||||||
@@ -121,7 +122,7 @@ async function QueryCacheHydration({ userId, boardId }: { userId: string; boardI
|
|||||||
const serialized = await getQueryCacheAsync(userId, boardId);
|
const serialized = await getQueryCacheAsync(userId, boardId);
|
||||||
if (!serialized) return null;
|
if (!serialized) return null;
|
||||||
|
|
||||||
const persisted = JSON.parse(serialized) as PersistedClient;
|
const persisted = SuperJSON.parse<PersistedClient>(serialized);
|
||||||
if (!persisted?.clientState?.queries?.length) return null;
|
if (!persisted?.clientState?.queries?.length) return null;
|
||||||
|
|
||||||
return <HydrationBoundary state={persisted.clientState} />;
|
return <HydrationBoundary state={persisted.clientState} />;
|
||||||
|
|||||||
@@ -14,17 +14,28 @@ interface Options<TData, TKind extends IntegrationKind, TInput extends Record<st
|
|||||||
requestAsync: (integration: IntegrationOfKind<TKind>, input: TInput) => Promise<TData>;
|
requestAsync: (integration: IntegrationOfKind<TKind>, input: TInput) => Promise<TData>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let integrationHandlerCounter = 0;
|
||||||
|
|
||||||
export const createIntegrationRequestHandler = <
|
export const createIntegrationRequestHandler = <
|
||||||
TData,
|
TData,
|
||||||
TKind extends IntegrationKind,
|
TKind extends IntegrationKind,
|
||||||
TInput extends Record<string, unknown>,
|
TInput extends Record<string, unknown>,
|
||||||
>(
|
>(
|
||||||
options: Options<TData, TKind, TInput>,
|
options: Options<TData, TKind, TInput>,
|
||||||
) => ({
|
) => {
|
||||||
handler: (integration: IntegrationOfKind<TKind>, itemOptions: TInput) => {
|
// Stable per handler definition: the inner request handler is re-created on every
|
||||||
const inner = createRequestHandler<TData, { integrationId: string; options: TInput }>({
|
// call, so without an explicit cacheKey each call would get a fresh namespace
|
||||||
requestAsync: async (input) => options.requestAsync(integration, input.options),
|
// (no cache hits) — and without any namespace different handlers hitting the same
|
||||||
});
|
// integration with equal options would share cache entries and cross their data.
|
||||||
return inner.handler({ integrationId: integration.id, options: itemOptions });
|
const cacheKey = `integration-handler-${integrationHandlerCounter++}`;
|
||||||
},
|
|
||||||
});
|
return {
|
||||||
|
handler: (integration: IntegrationOfKind<TKind>, itemOptions: TInput) => {
|
||||||
|
const inner = createRequestHandler<TData, { integrationId: string; options: TInput }>({
|
||||||
|
cacheKey,
|
||||||
|
requestAsync: async (input) => options.requestAsync(integration, input.options),
|
||||||
|
});
|
||||||
|
return inner.handler({ integrationId: integration.id, options: itemOptions });
|
||||||
|
},
|
||||||
|
};
|
||||||
|
};
|
||||||
@@ -1,6 +1,13 @@
|
|||||||
interface Options<TData, TInput extends Record<string, unknown>> {
|
interface Options<TData, TInput extends Record<string, unknown>> {
|
||||||
requestAsync: (input: TInput) => Promise<TData>;
|
requestAsync: (input: TInput) => Promise<TData>;
|
||||||
cacheTtlMs?: number;
|
cacheTtlMs?: number;
|
||||||
|
/**
|
||||||
|
* Namespace for cache entries of this handler. Defaults to a unique id per
|
||||||
|
* createRequestHandler call. Callers that re-create handlers per request
|
||||||
|
* (e.g. createIntegrationRequestHandler) must pass a stable key themselves,
|
||||||
|
* otherwise the cache never hits.
|
||||||
|
*/
|
||||||
|
cacheKey?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
type CacheEntry<TData> = { data: TData; timestamp: Date; expiresAt: number };
|
type CacheEntry<TData> = { data: TData; timestamp: Date; expiresAt: number };
|
||||||
@@ -18,43 +25,52 @@ const evictExpired = () => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
let autoCacheKeyCounter = 0;
|
||||||
|
|
||||||
export const createRequestHandler = <TData, TInput extends Record<string, unknown>>(
|
export const createRequestHandler = <TData, TInput extends Record<string, unknown>>(
|
||||||
options: Options<TData, TInput>,
|
options: Options<TData, TInput>,
|
||||||
) => ({
|
) => {
|
||||||
handler: (input: TInput) => ({
|
// The cache map is shared between all handlers, so entries have to be namespaced
|
||||||
async getDataAsync(): Promise<{ data: TData; timestamp: Date }> {
|
// per handler — otherwise handlers receiving the same input (e.g. the same
|
||||||
const ttl = options.cacheTtlMs ?? DEFAULT_TTL_MS;
|
// integrationId with empty options) would read each other's data.
|
||||||
const key = JSON.stringify(input);
|
const cacheKey = options.cacheKey ?? `handler-${autoCacheKeyCounter++}`;
|
||||||
|
|
||||||
const cached = cache.get(key) as CacheEntry<TData> | undefined;
|
return {
|
||||||
if (cached && Date.now() < cached.expiresAt) {
|
handler: (input: TInput) => ({
|
||||||
return { data: cached.data, timestamp: cached.timestamp };
|
async getDataAsync(): Promise<{ data: TData; timestamp: Date }> {
|
||||||
}
|
const ttl = options.cacheTtlMs ?? DEFAULT_TTL_MS;
|
||||||
if (cached) cache.delete(key);
|
const key = `${cacheKey}:${JSON.stringify(input)}`;
|
||||||
|
|
||||||
const existing = inflight.get(key);
|
const cached = cache.get(key) as CacheEntry<TData> | undefined;
|
||||||
if (existing) return existing as Promise<CacheEntry<TData>>;
|
if (cached && Date.now() < cached.expiresAt) {
|
||||||
|
return { data: cached.data, timestamp: cached.timestamp };
|
||||||
|
}
|
||||||
|
if (cached) cache.delete(key);
|
||||||
|
|
||||||
const promise = options
|
const existing = inflight.get(key);
|
||||||
.requestAsync(input)
|
if (existing) return existing as Promise<CacheEntry<TData>>;
|
||||||
.then((data) => {
|
|
||||||
if (cache.size >= MAX_CACHE_SIZE) evictExpired();
|
|
||||||
if (cache.size >= MAX_CACHE_SIZE) {
|
|
||||||
const oldest = cache.keys().next().value;
|
|
||||||
if (oldest) cache.delete(oldest);
|
|
||||||
}
|
|
||||||
const entry: CacheEntry<TData> = { data, timestamp: new Date(), expiresAt: Date.now() + ttl };
|
|
||||||
cache.set(key, entry as CacheEntry<unknown>);
|
|
||||||
inflight.delete(key);
|
|
||||||
return entry;
|
|
||||||
})
|
|
||||||
.catch((err) => {
|
|
||||||
inflight.delete(key);
|
|
||||||
throw err;
|
|
||||||
});
|
|
||||||
|
|
||||||
inflight.set(key, promise as Promise<CacheEntry<unknown>>);
|
const promise = options
|
||||||
return promise;
|
.requestAsync(input)
|
||||||
},
|
.then((data) => {
|
||||||
}),
|
if (cache.size >= MAX_CACHE_SIZE) evictExpired();
|
||||||
});
|
if (cache.size >= MAX_CACHE_SIZE) {
|
||||||
|
const oldest = cache.keys().next().value;
|
||||||
|
if (oldest) cache.delete(oldest);
|
||||||
|
}
|
||||||
|
const entry: CacheEntry<TData> = { data, timestamp: new Date(), expiresAt: Date.now() + ttl };
|
||||||
|
cache.set(key, entry as CacheEntry<unknown>);
|
||||||
|
inflight.delete(key);
|
||||||
|
return entry;
|
||||||
|
})
|
||||||
|
.catch((err) => {
|
||||||
|
inflight.delete(key);
|
||||||
|
throw err;
|
||||||
|
});
|
||||||
|
|
||||||
|
inflight.set(key, promise as Promise<CacheEntry<unknown>>);
|
||||||
|
return promise;
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
};
|
||||||
@@ -6,6 +6,7 @@ import { clientApi } from "@homarr/api/client";
|
|||||||
import { humanFileSize } from "@homarr/common";
|
import { humanFileSize } from "@homarr/common";
|
||||||
import { getIconUrl } from "@homarr/definitions";
|
import { getIconUrl } from "@homarr/definitions";
|
||||||
|
|
||||||
|
import { WidgetEmptyState } from "../common/empty-state";
|
||||||
import type { WidgetComponentProps } from "../definition";
|
import type { WidgetComponentProps } from "../definition";
|
||||||
|
|
||||||
export default function ArchiveTeamWarriorWidget({
|
export default function ArchiveTeamWarriorWidget({
|
||||||
@@ -28,7 +29,9 @@ const ArchiveTeamWarriorWidgetContent = ({
|
|||||||
integrationId: string;
|
integrationId: string;
|
||||||
options: WidgetComponentProps<"archiveTeamWarrior">["options"];
|
options: WidgetComponentProps<"archiveTeamWarrior">["options"];
|
||||||
}) => {
|
}) => {
|
||||||
const [data] = clientApi.widget.archiveTeamWarrior.getStatus.useSuspenseQuery({ integrationId });
|
const { data } = clientApi.widget.archiveTeamWarrior.getStatus.useQuery({ integrationId });
|
||||||
|
|
||||||
|
if (!data) return <WidgetEmptyState />;
|
||||||
|
|
||||||
const status = data.status;
|
const status = data.status;
|
||||||
const projectName = status.project?.title ?? status.selectedProject ?? "No project selected";
|
const projectName = status.project?.title ?? status.selectedProject ?? "No project selected";
|
||||||
|
|||||||
@@ -46,7 +46,7 @@ export function AudioStatsContent({ backend, stats, options, width }: AudioStats
|
|||||||
};
|
};
|
||||||
const navidromeStats = navidromeStatsByBackend[backend];
|
const navidromeStats = navidromeStatsByBackend[backend];
|
||||||
const showNowPlayingSection =
|
const showNowPlayingSection =
|
||||||
navidromeStats !== null && Boolean(options.showNowPlaying) && navidromeStats.nowPlaying.length > 0;
|
navidromeStats !== null && Boolean(options.showNowPlaying) && (navidromeStats.nowPlaying ?? []).length > 0;
|
||||||
|
|
||||||
const nowPlayingLimitByListVisibility = {
|
const nowPlayingLimitByListVisibility = {
|
||||||
true: options.maxNowPlayingItems ?? 3,
|
true: options.maxNowPlayingItems ?? 3,
|
||||||
@@ -54,7 +54,7 @@ export function AudioStatsContent({ backend, stats, options, width }: AudioStats
|
|||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
const nowPlayingTracks =
|
const nowPlayingTracks =
|
||||||
navidromeStats?.nowPlaying.slice(
|
(navidromeStats?.nowPlaying ?? []).slice(
|
||||||
0,
|
0,
|
||||||
nowPlayingLimitByListVisibility[
|
nowPlayingLimitByListVisibility[
|
||||||
String(options.showNowPlayingList) as keyof typeof nowPlayingLimitByListVisibility
|
String(options.showNowPlayingList) as keyof typeof nowPlayingLimitByListVisibility
|
||||||
|
|||||||
@@ -54,12 +54,12 @@ export default function BeszelAlertsWidget({
|
|||||||
}, [results]);
|
}, [results]);
|
||||||
|
|
||||||
const alerts = useMemo(
|
const alerts = useMemo(
|
||||||
() => results.flatMap((r) => r.alerts.map((a) => ({ ...a, _key: `${r.integrationId}:${a.id}` }))),
|
() => results.flatMap((r) => (r.alerts ?? []).map((a) => ({ ...a, _key: `${r.integrationId}:${a.id}` }))),
|
||||||
[results],
|
[results],
|
||||||
);
|
);
|
||||||
|
|
||||||
const history = useMemo(() => {
|
const history = useMemo(() => {
|
||||||
const all = results.flatMap((r) => r.history.map((h) => ({ ...h, _key: `${r.integrationId}:${h.id}` })));
|
const all = results.flatMap((r) => (r.history ?? []).map((h) => ({ ...h, _key: `${r.integrationId}:${h.id}` })));
|
||||||
return all
|
return all
|
||||||
.toSorted((a, b) => new Date(b.created).getTime() - new Date(a.created).getTime())
|
.toSorted((a, b) => new Date(b.created).getTime() - new Date(a.created).getTime())
|
||||||
.slice(0, options.maxHistoryItems);
|
.slice(0, options.maxHistoryItems);
|
||||||
|
|||||||
@@ -70,7 +70,7 @@ export default function BeszelSystemStatsWidget({
|
|||||||
} = clientApi.widget.beszel.getSystems.useQuery({ integrationIds });
|
} = clientApi.widget.beszel.getSystems.useQuery({ integrationIds });
|
||||||
|
|
||||||
const systems = useMemo(
|
const systems = useMemo(
|
||||||
() => systemsResult.flatMap((r) => r.systems.map((s) => ({ value: s.id, label: s.name }))),
|
() => systemsResult.flatMap((r) => (r.systems ?? []).map((s) => ({ value: s.id, label: s.name }))),
|
||||||
[systemsResult],
|
[systemsResult],
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -29,7 +29,7 @@ export const { definition, componentLoader } = createWidgetDefinition("beszelSys
|
|||||||
isPending,
|
isPending,
|
||||||
isError,
|
isError,
|
||||||
} = clientApi.widget.beszel.getSystems.useQuery({ integrationIds }, { enabled: integrationIds.length > 0 });
|
} = clientApi.widget.beszel.getSystems.useQuery({ integrationIds }, { enabled: integrationIds.length > 0 });
|
||||||
const selectData = data.flatMap((r) => r.systems.map((s) => ({ value: s.id, label: s.name })));
|
const selectData = data.flatMap((r) => (r.systems ?? []).map((s) => ({ value: s.id, label: s.name })));
|
||||||
return { data: selectData, isPending, isError };
|
return { data: selectData, isPending, isError };
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
|
|||||||
@@ -187,7 +187,7 @@ export const useDockerChartData = (
|
|||||||
const { fmt, ordered } = prepareRecords(containerStats, timePeriod);
|
const { fmt, ordered } = prepareRecords(containerStats, timePeriod);
|
||||||
const mapped = ordered.map((record) => {
|
const mapped = ordered.map((record) => {
|
||||||
const point: Record<string, unknown> = { time: fmt(record.created), rawTime: record.created };
|
const point: Record<string, unknown> = { time: fmt(record.created), rawTime: record.created };
|
||||||
const byName = new Map(record.stats.map((c) => [c.n, c]));
|
const byName = new Map((record.stats ?? []).map((c) => [c.n, c]));
|
||||||
for (const name of containerNames) {
|
for (const name of containerNames) {
|
||||||
point[name] = extract(byName.get(name));
|
point[name] = extract(byName.get(name));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,8 +13,8 @@ export const useBeszelFilteredSystems = (
|
|||||||
const allSystems = useMemo(
|
const allSystems = useMemo(
|
||||||
() =>
|
() =>
|
||||||
results
|
results
|
||||||
.flatMap((r) => r.systems.map((s) => ({ ...s, _key: `${r.integrationId}:${s.id}` })))
|
.flatMap((r) => (r.systems ?? []).map((s) => ({ ...s, _key: `${r.integrationId}:${s.id}` })))
|
||||||
.toSorted((a, b) => a.name.localeCompare(b.name)),
|
.toSorted((a, b) => (a.name ?? "").localeCompare(b.name ?? "")),
|
||||||
[results],
|
[results],
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -137,7 +137,7 @@ const CalendarBase = ({ isEditMode, events, month, setMonth, options }: Calendar
|
|||||||
.filter(
|
.filter(
|
||||||
(event) => event.metadata?.type !== "radarr" || options.releaseType.includes(event.metadata.releaseType),
|
(event) => event.metadata?.type !== "radarr" || options.releaseType.includes(event.metadata.releaseType),
|
||||||
)
|
)
|
||||||
.toSorted((eventA, eventB) => eventA.startDate.getTime() - eventB.startDate.getTime());
|
.toSorted((eventA, eventB) => new Date(eventA.startDate).getTime() - new Date(eventB.startDate).getTime());
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<CalendarDay
|
<CalendarDay
|
||||||
|
|||||||
@@ -32,22 +32,18 @@ export function InstanceCard({ instance, options, isTiny, widgetKey }: InstanceC
|
|||||||
defaultValue: ["applications"],
|
defaultValue: ["applications"],
|
||||||
});
|
});
|
||||||
|
|
||||||
const serverResourceCounts = buildServerResourceCounts(
|
const servers = instance.instanceInfo.servers ?? [];
|
||||||
instance.instanceInfo.servers,
|
const applications = instance.instanceInfo.applications ?? [];
|
||||||
instance.instanceInfo.applications,
|
const services = instance.instanceInfo.services ?? [];
|
||||||
instance.instanceInfo.services,
|
|
||||||
);
|
const serverResourceCounts = buildServerResourceCounts(servers, applications, services);
|
||||||
|
|
||||||
const baseUrl = instance.integrationUrl.replace(/\/+$/, "");
|
const baseUrl = instance.integrationUrl.replace(/\/+$/, "");
|
||||||
const relativeTime = useTimeAgo(instance.updatedAt);
|
const relativeTime = useTimeAgo(instance.updatedAt);
|
||||||
|
|
||||||
const onlineServers = instance.instanceInfo.servers.filter((s) => s.is_reachable !== false).length;
|
const onlineServers = servers.filter((s) => s.is_reachable !== false).length;
|
||||||
const runningApps = instance.instanceInfo.applications.filter(
|
const runningApps = applications.filter((a) => parseStatus(a.status ?? "") === "running").length;
|
||||||
(a) => parseStatus(a.status ?? "") === "running",
|
const runningServices = services.filter((s) => parseStatus(s.status ?? "") === "running").length;
|
||||||
).length;
|
|
||||||
const runningServices = instance.instanceInfo.services.filter(
|
|
||||||
(s) => parseStatus(s.status ?? "") === "running",
|
|
||||||
).length;
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Card p={0} radius="sm">
|
<Card p={0} radius="sm">
|
||||||
@@ -65,26 +61,18 @@ export function InstanceCard({ instance, options, isTiny, widgetKey }: InstanceC
|
|||||||
</Group>
|
</Group>
|
||||||
<Group gap={4} wrap="nowrap">
|
<Group gap={4} wrap="nowrap">
|
||||||
{options.showServers && (
|
{options.showServers && (
|
||||||
<Badge variant="dot" color={getBadgeColor(onlineServers, instance.instanceInfo.servers.length)} size="xs">
|
<Badge variant="dot" color={getBadgeColor(onlineServers, servers.length)} size="xs">
|
||||||
{onlineServers}/{instance.instanceInfo.servers.length}
|
{onlineServers}/{servers.length}
|
||||||
</Badge>
|
</Badge>
|
||||||
)}
|
)}
|
||||||
{options.showApplications && (
|
{options.showApplications && (
|
||||||
<Badge
|
<Badge variant="dot" color={getBadgeColor(runningApps, applications.length)} size="xs">
|
||||||
variant="dot"
|
{runningApps}/{applications.length}
|
||||||
color={getBadgeColor(runningApps, instance.instanceInfo.applications.length)}
|
|
||||||
size="xs"
|
|
||||||
>
|
|
||||||
{runningApps}/{instance.instanceInfo.applications.length}
|
|
||||||
</Badge>
|
</Badge>
|
||||||
)}
|
)}
|
||||||
{options.showServices && (
|
{options.showServices && (
|
||||||
<Badge
|
<Badge variant="dot" color={getBadgeColor(runningServices, services.length)} size="xs">
|
||||||
variant="dot"
|
{runningServices}/{services.length}
|
||||||
color={getBadgeColor(runningServices, instance.instanceInfo.services.length)}
|
|
||||||
size="xs"
|
|
||||||
>
|
|
||||||
{runningServices}/{instance.instanceInfo.services.length}
|
|
||||||
</Badge>
|
</Badge>
|
||||||
)}
|
)}
|
||||||
</Group>
|
</Group>
|
||||||
@@ -93,7 +81,7 @@ export function InstanceCard({ instance, options, isTiny, widgetKey }: InstanceC
|
|||||||
<Accordion variant="filled" chevronPosition="right" multiple value={openSections} onChange={setOpenSections}>
|
<Accordion variant="filled" chevronPosition="right" multiple value={openSections} onChange={setOpenSections}>
|
||||||
{options.showServers && (
|
{options.showServers && (
|
||||||
<ServersSection
|
<ServersSection
|
||||||
servers={instance.instanceInfo.servers}
|
servers={servers}
|
||||||
serverResourceCounts={serverResourceCounts}
|
serverResourceCounts={serverResourceCounts}
|
||||||
baseUrl={baseUrl}
|
baseUrl={baseUrl}
|
||||||
isTiny={isTiny}
|
isTiny={isTiny}
|
||||||
@@ -102,11 +90,9 @@ export function InstanceCard({ instance, options, isTiny, widgetKey }: InstanceC
|
|||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
{options.showApplications && (
|
{options.showApplications && (
|
||||||
<ApplicationsSection applications={instance.instanceInfo.applications} baseUrl={baseUrl} isTiny={isTiny} />
|
<ApplicationsSection applications={applications} baseUrl={baseUrl} isTiny={isTiny} />
|
||||||
)}
|
|
||||||
{options.showServices && (
|
|
||||||
<ServicesSection services={instance.instanceInfo.services} baseUrl={baseUrl} isTiny={isTiny} />
|
|
||||||
)}
|
)}
|
||||||
|
{options.showServices && <ServicesSection services={services} baseUrl={baseUrl} isTiny={isTiny} />}
|
||||||
</Accordion>
|
</Accordion>
|
||||||
|
|
||||||
<Group justify="space-between" p={4} style={{ borderTop: "1px solid var(--mantine-color-dark-4)" }}>
|
<Group justify="space-between" p={4} style={{ borderTop: "1px solid var(--mantine-color-dark-4)" }}>
|
||||||
|
|||||||
@@ -31,11 +31,11 @@ export function SingleInstanceLayout({ instance, options, isTiny, widgetKey }: S
|
|||||||
defaultValue: ["applications"],
|
defaultValue: ["applications"],
|
||||||
});
|
});
|
||||||
|
|
||||||
const serverResourceCounts = buildServerResourceCounts(
|
const servers = instance.instanceInfo.servers ?? [];
|
||||||
instance.instanceInfo.servers,
|
const applications = instance.instanceInfo.applications ?? [];
|
||||||
instance.instanceInfo.applications,
|
const services = instance.instanceInfo.services ?? [];
|
||||||
instance.instanceInfo.services,
|
|
||||||
);
|
const serverResourceCounts = buildServerResourceCounts(servers, applications, services);
|
||||||
|
|
||||||
const baseUrl = instance.integrationUrl.replace(/\/+$/, "");
|
const baseUrl = instance.integrationUrl.replace(/\/+$/, "");
|
||||||
const displayUrl = baseUrl.replace(/^https?:\/\//, "");
|
const displayUrl = baseUrl.replace(/^https?:\/\//, "");
|
||||||
@@ -59,7 +59,7 @@ export function SingleInstanceLayout({ instance, options, isTiny, widgetKey }: S
|
|||||||
<Accordion variant="contained" chevronPosition="right" multiple value={openSections} onChange={setOpenSections}>
|
<Accordion variant="contained" chevronPosition="right" multiple value={openSections} onChange={setOpenSections}>
|
||||||
{options.showServers && (
|
{options.showServers && (
|
||||||
<ServersSection
|
<ServersSection
|
||||||
servers={instance.instanceInfo.servers}
|
servers={servers}
|
||||||
serverResourceCounts={serverResourceCounts}
|
serverResourceCounts={serverResourceCounts}
|
||||||
baseUrl={baseUrl}
|
baseUrl={baseUrl}
|
||||||
isTiny={isTiny}
|
isTiny={isTiny}
|
||||||
@@ -68,11 +68,9 @@ export function SingleInstanceLayout({ instance, options, isTiny, widgetKey }: S
|
|||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
{options.showApplications && (
|
{options.showApplications && (
|
||||||
<ApplicationsSection applications={instance.instanceInfo.applications} baseUrl={baseUrl} isTiny={isTiny} />
|
<ApplicationsSection applications={applications} baseUrl={baseUrl} isTiny={isTiny} />
|
||||||
)}
|
|
||||||
{options.showServices && (
|
|
||||||
<ServicesSection services={instance.instanceInfo.services} baseUrl={baseUrl} isTiny={isTiny} />
|
|
||||||
)}
|
)}
|
||||||
|
{options.showServices && <ServicesSection services={services} baseUrl={baseUrl} isTiny={isTiny} />}
|
||||||
</Accordion>
|
</Accordion>
|
||||||
|
|
||||||
<Group
|
<Group
|
||||||
|
|||||||
@@ -104,7 +104,9 @@ export default function DownloadClientsWidget({
|
|||||||
const [quickFilters, setQuickFilters] = useState<QuickFilter>({ integrationKinds: [], statuses: [] });
|
const [quickFilters, setQuickFilters] = useState<QuickFilter>({ integrationKinds: [], statuses: [] });
|
||||||
const availableStatuses = useMemo<QuickFilter["statuses"]>(() => {
|
const availableStatuses = useMemo<QuickFilter["statuses"]>(() => {
|
||||||
//Redefine list of available statuses from current items
|
//Redefine list of available statuses from current items
|
||||||
const statuses = Array.from(new Set(currentItems.flatMap(({ data }) => data.items.map(({ state }) => state))));
|
const statuses = Array.from(
|
||||||
|
new Set(currentItems.flatMap(({ data }) => (data.items ?? []).map(({ state }) => state))),
|
||||||
|
);
|
||||||
//Reset user filters accordingly to remove unavailable statuses
|
//Reset user filters accordingly to remove unavailable statuses
|
||||||
setQuickFilters(({ integrationKinds: names, statuses: prevStatuses }) => {
|
setQuickFilters(({ integrationKinds: names, statuses: prevStatuses }) => {
|
||||||
return { integrationKinds: names, statuses: prevStatuses.filter((status) => statuses.includes(status)) };
|
return { integrationKinds: names, statuses: prevStatuses.filter((status) => statuses.includes(status)) };
|
||||||
@@ -127,7 +129,7 @@ export default function DownloadClientsWidget({
|
|||||||
//Construct normalized items list
|
//Construct normalized items list
|
||||||
.flatMap((pair) =>
|
.flatMap((pair) =>
|
||||||
//Apply user white/black list
|
//Apply user white/black list
|
||||||
pair.data.items
|
(pair.data.items ?? [])
|
||||||
.filter(
|
.filter(
|
||||||
({ category }) =>
|
({ category }) =>
|
||||||
options.filterIsWhitelist ===
|
options.filterIsWhitelist ===
|
||||||
@@ -202,7 +204,7 @@ export default function DownloadClientsWidget({
|
|||||||
const interact = integrationsWithInteractions.includes(integration.id);
|
const interact = integrationsWithInteractions.includes(integration.id);
|
||||||
const isTorrent = getIntegrationKindsByCategory("torrent").some((kind) => kind === integration.kind);
|
const isTorrent = getIntegrationKindsByCategory("torrent").some((kind) => kind === integration.kind);
|
||||||
/** Derived from current items */
|
/** Derived from current items */
|
||||||
const { totalUp, totalDown } = data.items
|
const { totalUp, totalDown } = (data.items ?? [])
|
||||||
.filter(
|
.filter(
|
||||||
({ category }) =>
|
({ category }) =>
|
||||||
!options.applyFilterToRatio ||
|
!options.applyFilterToRatio ||
|
||||||
|
|||||||
@@ -41,19 +41,21 @@ export const ClusterHealthMonitoring = ({
|
|||||||
|
|
||||||
if (!healthData) return <WidgetEmptyState />;
|
if (!healthData) return <WidgetEmptyState />;
|
||||||
|
|
||||||
const activeNodes = healthData.nodes.reduce(running, 0);
|
const nodes = healthData.nodes ?? [];
|
||||||
const activeVMs = healthData.vms.reduce(running, 0);
|
const vms = healthData.vms ?? [];
|
||||||
const activeLXCs = healthData.lxcs.reduce(running, 0);
|
const lxcs = healthData.lxcs ?? [];
|
||||||
const activeStorage = healthData.storages.reduce(running, 0);
|
const storages = healthData.storages ?? [];
|
||||||
|
|
||||||
const usedMem = healthData.nodes.reduce((sum, item) => (item.isRunning ? item.memory.used + sum : sum), 0);
|
const activeNodes = nodes.reduce(running, 0);
|
||||||
const maxMem = healthData.nodes.reduce((sum, item) => (item.isRunning ? item.memory.total + sum : sum), 0);
|
const activeVMs = vms.reduce(running, 0);
|
||||||
const maxCpu = healthData.nodes.reduce((sum, item) => (item.isRunning ? item.cpu.cores + sum : sum), 0);
|
const activeLXCs = lxcs.reduce(running, 0);
|
||||||
const usedCpu = healthData.nodes.reduce(
|
const activeStorage = storages.reduce(running, 0);
|
||||||
(sum, item) => (item.isRunning ? item.cpu.utilization * item.cpu.cores + sum : sum),
|
|
||||||
0,
|
const usedMem = nodes.reduce((sum, item) => (item.isRunning ? item.memory.used + sum : sum), 0);
|
||||||
);
|
const maxMem = nodes.reduce((sum, item) => (item.isRunning ? item.memory.total + sum : sum), 0);
|
||||||
const uptime = healthData.nodes.reduce((sum, { uptime }) => (sum > uptime ? sum : uptime), 0);
|
const maxCpu = nodes.reduce((sum, item) => (item.isRunning ? item.cpu.cores + sum : sum), 0);
|
||||||
|
const usedCpu = nodes.reduce((sum, item) => (item.isRunning ? item.cpu.utilization * item.cpu.cores + sum : sum), 0);
|
||||||
|
const uptime = nodes.reduce((sum, { uptime }) => (sum > uptime ? sum : uptime), 0);
|
||||||
|
|
||||||
const cpuPercent = maxCpu ? (usedCpu / maxCpu) * 100 : 0;
|
const cpuPercent = maxCpu ? (usedCpu / maxCpu) * 100 : 0;
|
||||||
const memPercent = maxMem ? (usedMem / maxMem) * 100 : 0;
|
const memPercent = maxMem ? (usedMem / maxMem) * 100 : 0;
|
||||||
@@ -89,12 +91,12 @@ export const ClusterHealthMonitoring = ({
|
|||||||
icon={IconServer}
|
icon={IconServer}
|
||||||
badge={addBadgeColor({
|
badge={addBadgeColor({
|
||||||
activeCount: activeNodes,
|
activeCount: activeNodes,
|
||||||
totalCount: healthData.nodes.length,
|
totalCount: nodes.length,
|
||||||
sectionIndicatorRequirement: options.sectionIndicatorRequirement,
|
sectionIndicatorRequirement: options.sectionIndicatorRequirement,
|
||||||
})}
|
})}
|
||||||
isTiny={isTiny}
|
isTiny={isTiny}
|
||||||
>
|
>
|
||||||
<ResourceTable type="node" data={healthData.nodes} isTiny={isTiny} />
|
<ResourceTable type="node" data={nodes} isTiny={isTiny} />
|
||||||
</ResourceAccordionItem>
|
</ResourceAccordionItem>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
@@ -105,12 +107,12 @@ export const ClusterHealthMonitoring = ({
|
|||||||
icon={IconDeviceLaptop}
|
icon={IconDeviceLaptop}
|
||||||
badge={addBadgeColor({
|
badge={addBadgeColor({
|
||||||
activeCount: activeVMs,
|
activeCount: activeVMs,
|
||||||
totalCount: healthData.vms.length,
|
totalCount: vms.length,
|
||||||
sectionIndicatorRequirement: options.sectionIndicatorRequirement,
|
sectionIndicatorRequirement: options.sectionIndicatorRequirement,
|
||||||
})}
|
})}
|
||||||
isTiny={isTiny}
|
isTiny={isTiny}
|
||||||
>
|
>
|
||||||
<ResourceTable type="qemu" data={healthData.vms} isTiny={isTiny} />
|
<ResourceTable type="qemu" data={vms} isTiny={isTiny} />
|
||||||
</ResourceAccordionItem>
|
</ResourceAccordionItem>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
@@ -121,12 +123,12 @@ export const ClusterHealthMonitoring = ({
|
|||||||
icon={IconCube}
|
icon={IconCube}
|
||||||
badge={addBadgeColor({
|
badge={addBadgeColor({
|
||||||
activeCount: activeLXCs,
|
activeCount: activeLXCs,
|
||||||
totalCount: healthData.lxcs.length,
|
totalCount: lxcs.length,
|
||||||
sectionIndicatorRequirement: options.sectionIndicatorRequirement,
|
sectionIndicatorRequirement: options.sectionIndicatorRequirement,
|
||||||
})}
|
})}
|
||||||
isTiny={isTiny}
|
isTiny={isTiny}
|
||||||
>
|
>
|
||||||
<ResourceTable type="lxc" data={healthData.lxcs} isTiny={isTiny} />
|
<ResourceTable type="lxc" data={lxcs} isTiny={isTiny} />
|
||||||
</ResourceAccordionItem>
|
</ResourceAccordionItem>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
@@ -137,12 +139,12 @@ export const ClusterHealthMonitoring = ({
|
|||||||
icon={IconDatabase}
|
icon={IconDatabase}
|
||||||
badge={addBadgeColor({
|
badge={addBadgeColor({
|
||||||
activeCount: activeStorage,
|
activeCount: activeStorage,
|
||||||
totalCount: healthData.storages.length,
|
totalCount: storages.length,
|
||||||
sectionIndicatorRequirement: options.sectionIndicatorRequirement,
|
sectionIndicatorRequirement: options.sectionIndicatorRequirement,
|
||||||
})}
|
})}
|
||||||
isTiny={isTiny}
|
isTiny={isTiny}
|
||||||
>
|
>
|
||||||
<ResourceTable type="storage" data={healthData.storages} isTiny={isTiny} />
|
<ResourceTable type="storage" data={storages} isTiny={isTiny} />
|
||||||
</ResourceAccordionItem>
|
</ResourceAccordionItem>
|
||||||
)}
|
)}
|
||||||
</Accordion>
|
</Accordion>
|
||||||
|
|||||||
@@ -65,7 +65,7 @@ export const SystemHealthMonitoring = ({
|
|||||||
return (
|
return (
|
||||||
<Stack h="100%" gap="sm" className="health-monitoring">
|
<Stack h="100%" gap="sm" className="health-monitoring">
|
||||||
{healthData.map(({ integrationId, integrationName, healthInfo }) => {
|
{healthData.map(({ integrationId, integrationName, healthInfo }) => {
|
||||||
const disksData = matchFileSystemAndSmart(healthInfo.fileSystem, healthInfo.smart);
|
const disksData = matchFileSystemAndSmart(healthInfo.fileSystem ?? [], healthInfo.smart ?? []);
|
||||||
const memoryUsage = formatMemoryUsage(healthInfo.memAvailableInBytes, healthInfo.memUsedInBytes);
|
const memoryUsage = formatMemoryUsage(healthInfo.memAvailableInBytes, healthInfo.memUsedInBytes);
|
||||||
return (
|
return (
|
||||||
<Stack
|
<Stack
|
||||||
@@ -165,7 +165,7 @@ export const SystemHealthMonitoring = ({
|
|||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
{options.gpu &&
|
{options.gpu &&
|
||||||
healthInfo.gpu.map((gpu) => (
|
(healthInfo.gpu ?? []).map((gpu) => (
|
||||||
<GpuRing key={gpu.gpuId} gpu={gpu} isTiny={isTiny} fahrenheit={options.fahrenheit} />
|
<GpuRing key={gpu.gpuId} gpu={gpu} isTiny={isTiny} fahrenheit={options.fahrenheit} />
|
||||||
))}
|
))}
|
||||||
</Flex>
|
</Flex>
|
||||||
@@ -301,5 +301,5 @@ export const matchFileSystemAndSmart = (fileSystems: FileSystem[], smartData: Sm
|
|||||||
overallStatus: smartDisk?.overallStatus ?? "",
|
overallStatus: smartDisk?.overallStatus ?? "",
|
||||||
};
|
};
|
||||||
})
|
})
|
||||||
.toSorted((fileSystemA, fileSystemB) => fileSystemA.deviceName.localeCompare(fileSystemB.deviceName));
|
.toSorted((fileSystemA, fileSystemB) => (fileSystemA.deviceName ?? "").localeCompare(fileSystemB.deviceName ?? ""));
|
||||||
};
|
};
|
||||||
@@ -65,7 +65,7 @@ export default function IndexerManagerWidget({
|
|||||||
<ScrollArea className="indexer-manager-list-scroll-area" h="100%" scrollbars="y">
|
<ScrollArea className="indexer-manager-list-scroll-area" h="100%" scrollbars="y">
|
||||||
{indexersData.map(({ integrationId, indexers }) => (
|
{indexersData.map(({ integrationId, indexers }) => (
|
||||||
<Stack gap={4} className={`indexer-manager-${integrationId}-list-container`} p={0} key={integrationId}>
|
<Stack gap={4} className={`indexer-manager-${integrationId}-list-container`} p={0} key={integrationId}>
|
||||||
{indexers.map((indexer) => (
|
{(indexers ?? []).map((indexer) => (
|
||||||
<Group
|
<Group
|
||||||
className={`indexer-manager-line indexer-manager-${indexer.name}`}
|
className={`indexer-manager-line indexer-manager-${indexer.name}`}
|
||||||
key={indexer.id}
|
key={indexer.id}
|
||||||
|
|||||||
@@ -80,7 +80,7 @@ const Item = ({ item, options }: ItemProps) => {
|
|||||||
top={0}
|
top={0}
|
||||||
left={0}
|
left={0}
|
||||||
style={{
|
style={{
|
||||||
backgroundImage: `url(${item.imageUrls.backdrop})`,
|
backgroundImage: `url(${item.imageUrls?.backdrop})`,
|
||||||
borderRadius: 8,
|
borderRadius: 8,
|
||||||
backgroundRepeat: "no-repeat",
|
backgroundRepeat: "no-repeat",
|
||||||
backgroundSize: "cover",
|
backgroundSize: "cover",
|
||||||
@@ -91,7 +91,7 @@ const Item = ({ item, options }: ItemProps) => {
|
|||||||
)}
|
)}
|
||||||
<Group justify="space-between" h="100%" wrap="nowrap">
|
<Group justify="space-between" h="100%" wrap="nowrap">
|
||||||
<Group align="start" wrap="nowrap" style={{ zIndex: 0 }}>
|
<Group align="start" wrap="nowrap" style={{ zIndex: 0 }}>
|
||||||
{options.layout === "poster" && <Image w={60} src={item.imageUrls.poster} alt={item.title} />}
|
{options.layout === "poster" && <Image w={60} src={item.imageUrls?.poster} alt={item.title} />}
|
||||||
<Stack gap={4}>
|
<Stack gap={4}>
|
||||||
<Stack gap={0}>
|
<Stack gap={0}>
|
||||||
<Text size="sm" fw="bold" lineClamp={2}>
|
<Text size="sm" fw="bold" lineClamp={2}>
|
||||||
@@ -130,7 +130,7 @@ const Item = ({ item, options }: ItemProps) => {
|
|||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</Group>
|
</Group>
|
||||||
{item.tags.length > 0 && (
|
{(item.tags ?? []).length > 0 && (
|
||||||
<OverflowBadge
|
<OverflowBadge
|
||||||
size="xs"
|
size="xs"
|
||||||
groupGap={4}
|
groupGap={4}
|
||||||
|
|||||||
@@ -43,48 +43,49 @@ export default function MediaServerWidget({
|
|||||||
const board = useRequiredBoard();
|
const board = useRequiredBoard();
|
||||||
|
|
||||||
if (!requestStats) return <WidgetEmptyState />;
|
if (!requestStats) return <WidgetEmptyState />;
|
||||||
if (requestStats.users.length === 0 && requestStats.stats.length === 0) throw new NoIntegrationDataError();
|
if ((requestStats.users ?? []).length === 0 && (requestStats.stats ?? []).length === 0)
|
||||||
|
throw new NoIntegrationDataError();
|
||||||
|
|
||||||
const data = [
|
const data = [
|
||||||
{
|
{
|
||||||
name: "approved",
|
name: "approved",
|
||||||
icon: IconThumbUp,
|
icon: IconThumbUp,
|
||||||
number: requestStats.stats.reduce((count, { approved }) => count + approved, 0),
|
number: (requestStats.stats ?? []).reduce((count, { approved }) => count + approved, 0),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "pending",
|
name: "pending",
|
||||||
icon: IconHourglass,
|
icon: IconHourglass,
|
||||||
number: requestStats.stats.reduce((count, { pending }) => count + pending, 0),
|
number: (requestStats.stats ?? []).reduce((count, { pending }) => count + pending, 0),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "processing",
|
name: "processing",
|
||||||
icon: IconLoaderQuarter,
|
icon: IconLoaderQuarter,
|
||||||
number: requestStats.stats.reduce((count, { processing }) => count + processing, 0),
|
number: (requestStats.stats ?? []).reduce((count, { processing }) => count + processing, 0),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "declined",
|
name: "declined",
|
||||||
icon: IconThumbDown,
|
icon: IconThumbDown,
|
||||||
number: requestStats.stats.reduce((count, { declined }) => count + declined, 0),
|
number: (requestStats.stats ?? []).reduce((count, { declined }) => count + declined, 0),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "available",
|
name: "available",
|
||||||
icon: IconPlayerPlay,
|
icon: IconPlayerPlay,
|
||||||
number: requestStats.stats.reduce((count, { available }) => count + available, 0),
|
number: (requestStats.stats ?? []).reduce((count, { available }) => count + available, 0),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "tv",
|
name: "tv",
|
||||||
icon: IconDeviceTv,
|
icon: IconDeviceTv,
|
||||||
number: requestStats.stats.reduce((count, { tv }) => count + tv, 0),
|
number: (requestStats.stats ?? []).reduce((count, { tv }) => count + tv, 0),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "movie",
|
name: "movie",
|
||||||
icon: IconMovie,
|
icon: IconMovie,
|
||||||
number: requestStats.stats.reduce((count, { movie }) => count + movie, 0),
|
number: (requestStats.stats ?? []).reduce((count, { movie }) => count + movie, 0),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "total",
|
name: "total",
|
||||||
icon: IconReceipt,
|
icon: IconReceipt,
|
||||||
number: requestStats.stats.reduce((count, { total }) => count + total, 0),
|
number: (requestStats.stats ?? []).reduce((count, { total }) => count + total, 0),
|
||||||
},
|
},
|
||||||
] satisfies { name: keyof RequestStats; icon: Icon; number: number }[];
|
] satisfies { name: keyof RequestStats; icon: Icon; number: number }[];
|
||||||
|
|
||||||
@@ -132,7 +133,7 @@ export default function MediaServerWidget({
|
|||||||
{t("titles.users.main")} ({t("titles.users.requests")})
|
{t("titles.users.main")} ({t("titles.users.requests")})
|
||||||
</Text>
|
</Text>
|
||||||
<Stack className="mediaRequests-stats-users-wrapper" flex={1} w="100%" gap={4} style={{ overflow: "hidden" }}>
|
<Stack className="mediaRequests-stats-users-wrapper" flex={1} w="100%" gap={4} style={{ overflow: "hidden" }}>
|
||||||
{requestStats.users.slice(0, 10).map((user) => (
|
{(requestStats.users ?? []).slice(0, 10).map((user) => (
|
||||||
<Card
|
<Card
|
||||||
component="a"
|
component="a"
|
||||||
href={user.link}
|
href={user.link}
|
||||||
|
|||||||
@@ -76,7 +76,7 @@ export default function MediaServerWidget({ options, integrationIds }: WidgetCom
|
|||||||
const flatSessions = useMemo(
|
const flatSessions = useMemo(
|
||||||
() =>
|
() =>
|
||||||
currentStreams.flatMap((pair) =>
|
currentStreams.flatMap((pair) =>
|
||||||
pair.sessions.map((session) => ({
|
(pair.sessions ?? []).map((session) => ({
|
||||||
...session,
|
...session,
|
||||||
integrationKind: pair.integrationKind,
|
integrationKind: pair.integrationKind,
|
||||||
integrationName: integrationDefs[pair.integrationKind].name,
|
integrationName: integrationDefs[pair.integrationKind].name,
|
||||||
|
|||||||
@@ -27,7 +27,7 @@ export function QueuePanel(props: QueuePanelProps) {
|
|||||||
|
|
||||||
const t = useI18n("widget.mediaTranscoding.panel.queue");
|
const t = useI18n("widget.mediaTranscoding.panel.queue");
|
||||||
|
|
||||||
if (queue.array.length === 0) {
|
if ((queue.array ?? []).length === 0) {
|
||||||
return (
|
return (
|
||||||
<Center style={{ flex: "1" }}>
|
<Center style={{ flex: "1" }}>
|
||||||
<Title order={6}>{t("empty")}</Title>
|
<Title order={6}>{t("empty")}</Title>
|
||||||
@@ -53,7 +53,7 @@ export function QueuePanel(props: QueuePanelProps) {
|
|||||||
</TableTr>
|
</TableTr>
|
||||||
</TableThead>
|
</TableThead>
|
||||||
<TableTbody>
|
<TableTbody>
|
||||||
{queue.array.map((item) => (
|
{(queue.array ?? []).map((item) => (
|
||||||
<TableTr key={item.id}>
|
<TableTr key={item.id}>
|
||||||
<TableTd py={2}>
|
<TableTd py={2}>
|
||||||
<Group gap={4} wrap="nowrap">
|
<Group gap={4} wrap="nowrap">
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ interface WorkersPanelProps {
|
|||||||
export function WorkersPanel(props: WorkersPanelProps) {
|
export function WorkersPanel(props: WorkersPanelProps) {
|
||||||
const t = useI18n("widget.mediaTranscoding.panel.workers");
|
const t = useI18n("widget.mediaTranscoding.panel.workers");
|
||||||
|
|
||||||
if (props.workers.length === 0) {
|
if ((props.workers ?? []).length === 0) {
|
||||||
return (
|
return (
|
||||||
<Center style={{ flex: "1" }}>
|
<Center style={{ flex: "1" }}>
|
||||||
<Title order={6}>{t("empty")}</Title>
|
<Title order={6}>{t("empty")}</Title>
|
||||||
|
|||||||
@@ -25,19 +25,19 @@ export default function NetworkControllerNetworkStatusWidget({
|
|||||||
integrationIds,
|
integrationIds,
|
||||||
});
|
});
|
||||||
|
|
||||||
const data = useMemo(() => summaries.flatMap(({ summary }) => summary), [summaries]);
|
const data = useMemo(() => summaries.flatMap(({ summary }) => (summary ? [summary] : [])), [summaries]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Box p={"sm"}>
|
<Box p={"sm"}>
|
||||||
{options.content === "wifi" ? (
|
{options.content === "wifi" ? (
|
||||||
<WifiVariant
|
<WifiVariant
|
||||||
countGuests={data.reduce((sum, summary) => sum + summary.wifi.guests, 0)}
|
countGuests={data.reduce((sum, summary) => sum + (summary.wifi?.guests ?? 0), 0)}
|
||||||
countUsers={data.reduce((sum, summary) => sum + summary.wifi.users, 0)}
|
countUsers={data.reduce((sum, summary) => sum + (summary.wifi?.users ?? 0), 0)}
|
||||||
/>
|
/>
|
||||||
) : (
|
) : (
|
||||||
<WiredVariant
|
<WiredVariant
|
||||||
countGuests={data.reduce((sum, summary) => sum + summary.lan.guests, 0)}
|
countGuests={data.reduce((sum, summary) => sum + (summary.lan?.guests ?? 0), 0)}
|
||||||
countUsers={data.reduce((sum, summary) => sum + summary.lan.users, 0)}
|
countUsers={data.reduce((sum, summary) => sum + (summary.lan?.users ?? 0), 0)}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
</Box>
|
</Box>
|
||||||
|
|||||||
@@ -24,8 +24,8 @@ export default function NotificationsWidget({ options, integrationIds }: WidgetC
|
|||||||
const sortedNotifications = useMemo(
|
const sortedNotifications = useMemo(
|
||||||
() =>
|
() =>
|
||||||
notificationIntegrations
|
notificationIntegrations
|
||||||
.flatMap((integration) => integration.data)
|
.flatMap((integration) => integration.data ?? [])
|
||||||
.sort((entryA, entryB) => entryB.time.getTime() - entryA.time.getTime()),
|
.sort((a, b) => (b.time?.getTime?.() ?? 0) - (a.time?.getTime?.() ?? 0)),
|
||||||
[notificationIntegrations],
|
[notificationIntegrations],
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ export default function SpeedtestTrackerWidget({ options, integrationIds }: Widg
|
|||||||
(acc, item) => ({
|
(acc, item) => ({
|
||||||
latestResult: item.dashboard.latestResult ?? acc.latestResult,
|
latestResult: item.dashboard.latestResult ?? acc.latestResult,
|
||||||
stats: mergeStats(acc.stats, item.dashboard.stats),
|
stats: mergeStats(acc.stats, item.dashboard.stats),
|
||||||
recentResults: [...acc.recentResults, ...item.dashboard.recentResults],
|
recentResults: [...acc.recentResults, ...(item.dashboard.recentResults ?? [])],
|
||||||
}),
|
}),
|
||||||
{ latestResult: null, stats: null, recentResults: [] },
|
{ latestResult: null, stats: null, recentResults: [] },
|
||||||
),
|
),
|
||||||
@@ -32,7 +32,9 @@ export default function SpeedtestTrackerWidget({ options, integrationIds }: Widg
|
|||||||
);
|
);
|
||||||
|
|
||||||
const twelveHoursAgo = Date.now() - 12 * 60 * 60 * 1000;
|
const twelveHoursAgo = Date.now() - 12 * 60 * 60 * 1000;
|
||||||
const recentFiltered = combined.recentResults.filter((result) => result.created_at.getTime() > twelveHoursAgo);
|
const recentFiltered = combined.recentResults.filter(
|
||||||
|
(result) => new Date(result.created_at).getTime() > twelveHoursAgo,
|
||||||
|
);
|
||||||
|
|
||||||
const hasStatSection =
|
const hasStatSection =
|
||||||
(options.showLatestResult && combined.latestResult !== null) || (options.showStats && combined.stats !== null);
|
(options.showLatestResult && combined.latestResult !== null) || (options.showStats && combined.stats !== null);
|
||||||
|
|||||||
@@ -40,7 +40,7 @@ function buildXAxisTicks(data: { ts: number }[]): XAxisTicks {
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
midnightTs: foundMidnight,
|
midnightTs: foundMidnight,
|
||||||
xTicks: Array.from(tickSet).sort((tsA, tsB) => tsA - tsB),
|
xTicks: Array.from(tickSet).toSorted((tsA, tsB) => tsA - tsB),
|
||||||
topDateTicks: topTicks,
|
topDateTicks: topTicks,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -161,10 +161,10 @@ function SpeedHistoryChart({ results, height }: { results: SpeedtestTrackerResul
|
|||||||
const data = useMemo(
|
const data = useMemo(
|
||||||
() =>
|
() =>
|
||||||
[...results]
|
[...results]
|
||||||
.sort((resultA, resultB) => resultA.created_at.getTime() - resultB.created_at.getTime())
|
.toSorted((resultA, resultB) => new Date(resultA.created_at).getTime() - new Date(resultB.created_at).getTime())
|
||||||
.filter((result) => (result.download_bits ?? 0) > 0)
|
.filter((result) => (result.download_bits ?? 0) > 0)
|
||||||
.map((result) => ({
|
.map((result) => ({
|
||||||
ts: result.created_at.getTime(),
|
ts: new Date(result.created_at).getTime(),
|
||||||
Download: parseFloat(((result.download_bits ?? 0) / 1_000_000).toFixed(2)),
|
Download: parseFloat(((result.download_bits ?? 0) / 1_000_000).toFixed(2)),
|
||||||
Upload:
|
Upload:
|
||||||
result.upload_bits != null && result.upload_bits > 0
|
result.upload_bits != null && result.upload_bits > 0
|
||||||
@@ -273,12 +273,12 @@ function PingHistoryChart({ results, height }: { results: SpeedtestTrackerResult
|
|||||||
const data = useMemo(
|
const data = useMemo(
|
||||||
() =>
|
() =>
|
||||||
[...results]
|
[...results]
|
||||||
.sort((resultA, resultB) => resultA.created_at.getTime() - resultB.created_at.getTime())
|
.toSorted((resultA, resultB) => new Date(resultA.created_at).getTime() - new Date(resultB.created_at).getTime())
|
||||||
.map((result) =>
|
.map((result) =>
|
||||||
result.ping === null
|
result.ping === null
|
||||||
? null
|
? null
|
||||||
: {
|
: {
|
||||||
ts: result.created_at.getTime(),
|
ts: new Date(result.created_at).getTime(),
|
||||||
Ping: result.ping,
|
Ping: result.ping,
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -35,8 +35,9 @@ export default function StockPriceWidget({ options, width, height }: WidgetCompo
|
|||||||
calculateChangePercentage(data.priceHistory.at(-1) ?? 0, data.previousClose),
|
calculateChangePercentage(data.priceHistory.at(-1) ?? 0, data.previousClose),
|
||||||
);
|
);
|
||||||
|
|
||||||
const stockValuesMin = Math.min(...data.priceHistory);
|
const priceHistory = data.priceHistory ?? [];
|
||||||
const stockGraphValues = data.priceHistory.map((value) => value - stockValuesMin + 50);
|
const stockValuesMin = priceHistory.length > 0 ? Math.min(...priceHistory) : 0;
|
||||||
|
const stockGraphValues = priceHistory.map((value) => value - stockValuesMin + 50);
|
||||||
const trendColor = stockValuesChange > 0 ? "green.7" : stockValuesChange < 0 ? "red.7" : "gray.6";
|
const trendColor = stockValuesChange > 0 ? "green.7" : stockValuesChange < 0 ? "red.7" : "gray.6";
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|||||||
@@ -34,7 +34,7 @@ const TimetableWidgetInner = ({ station, baseUrl }: TimetableWidgetInnerProps) =
|
|||||||
<Stack w="100%" gap="xs" p="sm">
|
<Stack w="100%" gap="xs" p="sm">
|
||||||
<Text fw="bold">{t("title", { station: station.label })}</Text>
|
<Text fw="bold">{t("title", { station: station.label })}</Text>
|
||||||
{(timetable?.entries ?? []).map((entry) => (
|
{(timetable?.entries ?? []).map((entry) => (
|
||||||
<Group key={`${entry.timestamp.toISOString()}-${entry.location}`} justify="space-between" w="100%">
|
<Group key={`${new Date(entry.timestamp).toISOString()}-${entry.location}`} justify="space-between" w="100%">
|
||||||
<Group gap="sm">
|
<Group gap="sm">
|
||||||
{entry.line && (
|
{entry.line && (
|
||||||
<Badge
|
<Badge
|
||||||
|
|||||||
@@ -37,24 +37,28 @@ function TracearrContent({ integrationIds, options, width }: TracearrContentProp
|
|||||||
const { stats, streams, violations, recentActivity } = item.dashboard;
|
const { stats, streams, violations, recentActivity } = item.dashboard;
|
||||||
const vData = violations ?? { data: [], meta: { total: 0, page: 1, pageSize: 5 } };
|
const vData = violations ?? { data: [], meta: { total: 0, page: 1, pageSize: 5 } };
|
||||||
const aData = recentActivity ?? { data: [], meta: { total: 0, page: 1, pageSize: 5 } };
|
const aData = recentActivity ?? { data: [], meta: { total: 0, page: 1, pageSize: 5 } };
|
||||||
|
const sData = streams ?? {
|
||||||
|
data: [],
|
||||||
|
summary: { total: 0, transcodes: 0, directStreams: 0, directPlays: 0, totalBitrate: "0", byServer: [] },
|
||||||
|
};
|
||||||
|
|
||||||
return {
|
return {
|
||||||
stats: {
|
stats: {
|
||||||
activeStreams: acc.stats.activeStreams + stats.activeStreams,
|
activeStreams: acc.stats.activeStreams + (stats?.activeStreams ?? 0),
|
||||||
totalUsers: acc.stats.totalUsers + stats.totalUsers,
|
totalUsers: acc.stats.totalUsers + (stats?.totalUsers ?? 0),
|
||||||
totalSessions: acc.stats.totalSessions + stats.totalSessions,
|
totalSessions: acc.stats.totalSessions + (stats?.totalSessions ?? 0),
|
||||||
recentViolations: acc.stats.recentViolations + stats.recentViolations,
|
recentViolations: acc.stats.recentViolations + (stats?.recentViolations ?? 0),
|
||||||
timestamp: stats.timestamp,
|
timestamp: stats?.timestamp ?? "",
|
||||||
},
|
},
|
||||||
streams: {
|
streams: {
|
||||||
data: [...acc.streams.data, ...streams.data],
|
data: [...acc.streams.data, ...(sData.data ?? [])],
|
||||||
summary: {
|
summary: {
|
||||||
total: acc.streams.summary.total + streams.summary.total,
|
total: acc.streams.summary.total + (sData.summary?.total ?? 0),
|
||||||
transcodes: acc.streams.summary.transcodes + streams.summary.transcodes,
|
transcodes: acc.streams.summary.transcodes + (sData.summary?.transcodes ?? 0),
|
||||||
directStreams: acc.streams.summary.directStreams + streams.summary.directStreams,
|
directStreams: acc.streams.summary.directStreams + (sData.summary?.directStreams ?? 0),
|
||||||
directPlays: acc.streams.summary.directPlays + streams.summary.directPlays,
|
directPlays: acc.streams.summary.directPlays + (sData.summary?.directPlays ?? 0),
|
||||||
totalBitrate: streams.summary.totalBitrate,
|
totalBitrate: sData.summary?.totalBitrate ?? "0",
|
||||||
byServer: [...acc.streams.summary.byServer, ...streams.summary.byServer],
|
byServer: [...acc.streams.summary.byServer, ...(sData.summary?.byServer ?? [])],
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
violations: {
|
violations: {
|
||||||
|
|||||||
@@ -57,7 +57,7 @@ export function UmamiContent({
|
|||||||
);
|
);
|
||||||
|
|
||||||
const multiEventTotal = multiEventSeries
|
const multiEventTotal = multiEventSeries
|
||||||
? multiEventSeries.flatMap(({ dataPoints }) => dataPoints).reduce((sum, { y }) => sum + y, 0)
|
? multiEventSeries.flatMap(({ dataPoints }) => dataPoints ?? []).reduce((sum, { y }) => sum + y, 0)
|
||||||
: undefined;
|
: undefined;
|
||||||
|
|
||||||
const firstResult = results[0];
|
const firstResult = results[0];
|
||||||
@@ -73,13 +73,13 @@ export function UmamiContent({
|
|||||||
|
|
||||||
const { visitorStats } = firstResult;
|
const { visitorStats } = firstResult;
|
||||||
|
|
||||||
const chartData = visitorStats.dataPoints.map((point: UmamiVisitorStats["dataPoints"][number]) => ({
|
const chartData = (visitorStats.dataPoints ?? []).map((point: UmamiVisitorStats["dataPoints"][number]) => ({
|
||||||
label: formatXLabel(point.timestamp, timeFrame),
|
label: formatXLabel(point.timestamp, timeFrame),
|
||||||
visitors: point.visitors,
|
visitors: point.visitors,
|
||||||
...(point.events !== undefined ? { events: point.events } : {}),
|
...(point.events !== undefined ? { events: point.events } : {}),
|
||||||
}));
|
}));
|
||||||
|
|
||||||
const hasEventSeries = visitorStats.dataPoints.some(({ events }) => events !== undefined);
|
const hasEventSeries = (visitorStats.dataPoints ?? []).some(({ events }) => events !== undefined);
|
||||||
const series = [
|
const series = [
|
||||||
{ name: "visitors", color: "blue.5" },
|
{ name: "visitors", color: "blue.5" },
|
||||||
...(hasEventSeries ? [{ name: "events", color: "orange.5" }] : []),
|
...(hasEventSeries ? [{ name: "events", color: "orange.5" }] : []),
|
||||||
|
|||||||
@@ -45,14 +45,14 @@ export function UmamiEventsContent({
|
|||||||
|
|
||||||
// Collect all unique timestamps across all series
|
// Collect all unique timestamps across all series
|
||||||
const allTimestamps = Array.from(
|
const allTimestamps = Array.from(
|
||||||
new Set(series.flatMap(({ dataPoints }) => dataPoints.map(({ x: xPoint }) => xPoint))),
|
new Set(series.flatMap(({ dataPoints }) => (dataPoints ?? []).map(({ x: xPoint }) => xPoint))),
|
||||||
).toSorted();
|
).toSorted();
|
||||||
|
|
||||||
// Build per-event lookup by timestamp string
|
// Build per-event lookup by timestamp string
|
||||||
const byEvent = new Map(
|
const byEvent = new Map(
|
||||||
series.map((serie: UmamiEventSeries) => [
|
series.map((serie: UmamiEventSeries) => [
|
||||||
serie.eventName,
|
serie.eventName,
|
||||||
new Map(serie.dataPoints.map((point) => [point.x, point.y])),
|
new Map((serie.dataPoints ?? []).map((point) => [point.x, point.y])),
|
||||||
]),
|
]),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -44,7 +44,7 @@ function UpsContent({ integrationIds, options, width }: UpsContentProps) {
|
|||||||
if (!data) return <WidgetEmptyState />;
|
if (!data) return <WidgetEmptyState />;
|
||||||
|
|
||||||
const devices = data.flatMap((instance) =>
|
const devices = data.flatMap((instance) =>
|
||||||
instance.summaries.map((summary) => ({ key: `${instance.integrationId}:${summary.id}`, summary })),
|
(instance.summaries ?? []).map((summary) => ({ key: `${instance.integrationId}:${summary.id}`, summary })),
|
||||||
);
|
);
|
||||||
|
|
||||||
if (devices.length === 0) {
|
if (devices.length === 0) {
|
||||||
|
|||||||
@@ -112,7 +112,7 @@ function UptimeKumaContent({ integrationIds, options, width }: UptimeKumaContent
|
|||||||
downCount: acc.downCount + item.dashboard.downCount,
|
downCount: acc.downCount + item.dashboard.downCount,
|
||||||
pausedCount: acc.pausedCount + item.dashboard.pausedCount,
|
pausedCount: acc.pausedCount + item.dashboard.pausedCount,
|
||||||
averageUptimePercent: acc.averageUptimePercent + item.dashboard.averageUptimePercent,
|
averageUptimePercent: acc.averageUptimePercent + item.dashboard.averageUptimePercent,
|
||||||
monitors: [...acc.monitors, ...item.dashboard.monitors],
|
monitors: [...acc.monitors, ...(item.dashboard.monitors ?? [])],
|
||||||
}),
|
}),
|
||||||
emptyDashboard,
|
emptyDashboard,
|
||||||
);
|
);
|
||||||
|
|||||||
Reference in new issue
Block a user