mirror of
https://github.com/gethomepage/homepage.git
synced 2026-09-23 12:35:48 -07:00
Compare commits
13 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| df52670871 | |||
| 3b26d0d3f6 | |||
| 76ad5d03cc | |||
| 9c3544eeef | |||
| e031209d68 | |||
| 802201d2a9 | |||
| 8619f93ab4 | |||
| d1c1ee7a1e | |||
| e0be80085e | |||
| b8ed72a03f | |||
| ebff6f4a7d | |||
| e890b544dc | |||
| f7666df9d8 |
@@ -23,7 +23,7 @@ jobs:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- name: crowdin action
|
||||
uses: crowdin/github-action@71fdb8814261dd703be4ca7c6450d21b1868da4b # v3.0.1
|
||||
uses: crowdin/github-action@0d5670f539973aea2f01abce61a8989934df0025 # v3.0.2
|
||||
with:
|
||||
upload_translations: false
|
||||
download_translations: true
|
||||
|
||||
@@ -62,7 +62,7 @@ jobs:
|
||||
nextjs-${{ runner.os }}-${{ hashFiles('pnpm-lock.yaml') }}
|
||||
|
||||
- name: Install pnpm
|
||||
uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86 # v6.0.10
|
||||
uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0
|
||||
with:
|
||||
version: 10
|
||||
run_install: false
|
||||
|
||||
@@ -23,7 +23,7 @@ jobs:
|
||||
with:
|
||||
python-version-file: ".python-version"
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@20cfd1bf945f4377ade1205e4dbc17946fc9a30d # v10.0.1
|
||||
uses: astral-sh/setup-uv@bec219d24cd3e171d82865faccec33120bb574f4 # v10.1.0
|
||||
- run: sudo apt-get install pngquant
|
||||
- name: Test Docs Build
|
||||
run: uv run --frozen zensical build --clean
|
||||
@@ -45,7 +45,7 @@ jobs:
|
||||
with:
|
||||
python-version-file: ".python-version"
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@20cfd1bf945f4377ade1205e4dbc17946fc9a30d # v10.0.1
|
||||
uses: astral-sh/setup-uv@bec219d24cd3e171d82865faccec33120bb574f4 # v10.1.0
|
||||
- run: sudo apt-get install pngquant
|
||||
- name: Build Docs
|
||||
run: uv run --frozen zensical build --clean
|
||||
|
||||
@@ -26,7 +26,7 @@ jobs:
|
||||
uses: pre-commit/action@2c7b3805fd2a0fd8c1884dcaebf91fc102a13ecd # v3.0.1
|
||||
|
||||
- name: Install pnpm
|
||||
uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86 # v6.0.10
|
||||
uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0
|
||||
with:
|
||||
version: 10
|
||||
run_install: false
|
||||
|
||||
@@ -18,7 +18,7 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
|
||||
- uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86 # v6.0.10
|
||||
- uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0
|
||||
with:
|
||||
version: 9
|
||||
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 11 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 11 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 11 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 11 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 11 KiB |
@@ -430,6 +430,64 @@ headerStyle: clean
|
||||
headerStyle: boxedWidgets
|
||||
```
|
||||
|
||||
## Card Style
|
||||
|
||||
Service and bookmark cards use a drop shadow by default. The `hairline` style replaces it with a thin border that brightens on hover.
|
||||
|
||||
<img width="896" alt="default cards" src="../../assets/style-default.webp">
|
||||
|
||||
```yaml
|
||||
# default, shadowed cards
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
<img width="896" alt="hairline cards" src="../../assets/card-style-hairline.webp">
|
||||
|
||||
```yaml
|
||||
cardStyle: hairline
|
||||
```
|
||||
|
||||
## Block Style
|
||||
|
||||
Widget blocks (the value / label pairs inside a service card) can use the `refined` style to make values heavier and easier to read.
|
||||
|
||||
<img width="896" alt="default blocks" src="../../assets/style-default.webp">
|
||||
|
||||
```yaml
|
||||
# default, standard blocks
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
<img width="896" alt="refined blocks" src="../../assets/block-style-refined.webp">
|
||||
|
||||
```yaml
|
||||
blockStyle: refined
|
||||
```
|
||||
|
||||
## Font
|
||||
|
||||
Homepage uses Manrope by default. You can switch to IBM Plex Mono instead, either everywhere or for data only.
|
||||
|
||||
<img width="896" alt="IBM Plex Mono everywhere" src="../../assets/font-plex.webp">
|
||||
|
||||
```yaml
|
||||
font: plex # the whole dashboard
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
<img width="896" alt="IBM Plex Mono for data only" src="../../assets/font-plex-data.webp">
|
||||
|
||||
```yaml
|
||||
font: plexData # only values, stats, the clock and status tags
|
||||
```
|
||||
|
||||
With `plexData`, labels and names stay in Manrope while numbers line up in columns.
|
||||
|
||||
Both fonts are bundled with Homepage, so no external requests are made.
|
||||
|
||||
## Base URL
|
||||
|
||||
In some proxy configurations, it may be necessary to set the documents base URL. You can do this by providing a `base` value, like so:
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
---
|
||||
title: Custom API
|
||||
description: Custom API Information Widget Configuration
|
||||
---
|
||||
|
||||
_(Find the Custom API service widget [here](../services/customapi.md))_
|
||||
|
||||
The Custom API information widget shows values from a custom self-hosted or third party API in your Homepage header, alongside an icon.
|
||||
|
||||
```yaml
|
||||
- customapi:
|
||||
url: http://custom.api.host.or.ip:port/path/to/exact/api/endpoint
|
||||
icon: mdi-api # optional, see below
|
||||
label: My API # optional, shown below the values
|
||||
href: https://custom.api.host # optional, makes the widget a link
|
||||
refreshInterval: 10000 # optional - in milliseconds, defaults to 10s
|
||||
username: username # auth - optional
|
||||
password: password # auth - optional
|
||||
method: GET # optional, e.g. POST
|
||||
headers: # optional, must be object
|
||||
X-API-Token: token
|
||||
requestBody: # optional, can be string or object
|
||||
mappings:
|
||||
- field: key
|
||||
label: Field 1
|
||||
- field: path.to.key2
|
||||
label: Field 2
|
||||
format: number # optional - defaults to text
|
||||
- field: path.to.key3
|
||||
label: Field 3
|
||||
format: percent
|
||||
```
|
||||
|
||||
The `icon` accepts the same values as [service icons](../../configs/services.md#icons), e.g. `mdi-api`, `si-github`, `sh-homepage`, a dashboard icon name like `homepage.png`, or a full URL. If no icon is set, a generic API icon is shown.
|
||||
|
||||
Mappings support the same `field`, `format`, `remap`, `scale`, `prefix` and `suffix` options as the [Custom API service widget](../services/customapi.md). The `additionalField` option and the `display` modes are not supported.
|
||||
@@ -7,6 +7,7 @@ search:
|
||||
|
||||
You can also find a list of all available info widgets in the sidebar navigation.
|
||||
|
||||
- [Custom API](customapi.md)
|
||||
- [Date & Time](datetime.md)
|
||||
- [Glances](glances.md)
|
||||
- [Greeting](greeting.md)
|
||||
|
||||
@@ -3,6 +3,8 @@ title: Custom API
|
||||
description: Custom Widget Configuration from the API
|
||||
---
|
||||
|
||||
_(Find the Custom API information widget [here](../info/customapi.md))_
|
||||
|
||||
This widget can show information from custom self-hosted or third party API.
|
||||
|
||||
Fields need to be defined in the `mappings` section YAML object to correlate with the value in the APIs JSON object. Final field definition needs to be the key with the desired value information.
|
||||
|
||||
@@ -194,6 +194,7 @@ nav:
|
||||
- widgets/services/zabbix.md
|
||||
- "Information Widgets":
|
||||
- widgets/info/index.md
|
||||
- widgets/info/customapi.md
|
||||
- widgets/info/datetime.md
|
||||
- widgets/info/glances.md
|
||||
- widgets/info/greeting.md
|
||||
|
||||
@@ -39,6 +39,7 @@
|
||||
"react-i18next": "^17.0.12",
|
||||
"react-icons": "^5.6.0",
|
||||
"recharts": "^3.1.2",
|
||||
"sax": "^1.6.1",
|
||||
"swr": "^2.5.1",
|
||||
"systeminformation": "^5.33.1",
|
||||
"tough-cookie": "^6.0.2",
|
||||
|
||||
Generated
+3
@@ -83,6 +83,9 @@ importers:
|
||||
recharts:
|
||||
specifier: ^3.1.2
|
||||
version: 3.10.1(@types/react@19.2.18)(react-dom@19.2.8(react@19.2.8))(react-is@17.0.2)(react@19.2.8)(redux@5.0.1)
|
||||
sax:
|
||||
specifier: ^1.6.1
|
||||
version: 1.6.1
|
||||
swr:
|
||||
specifier: ^2.5.1
|
||||
version: 2.5.1(react@19.2.8)
|
||||
|
||||
@@ -1258,5 +1258,8 @@
|
||||
"wanted": "Wanted",
|
||||
"queued": "Queued",
|
||||
"leagues": "Leagues"
|
||||
},
|
||||
"feed": {
|
||||
"noItems": "No items"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import createMockRes from "test-utils/create-mock-res";
|
||||
|
||||
const { getPrivateWidgetOptions, httpProxy, logger } = vi.hoisted(() => ({
|
||||
getPrivateWidgetOptions: vi.fn(),
|
||||
httpProxy: vi.fn(),
|
||||
logger: { debug: vi.fn() },
|
||||
}));
|
||||
|
||||
vi.mock("utils/config/widget-helpers", () => ({
|
||||
getPrivateWidgetOptions,
|
||||
}));
|
||||
|
||||
vi.mock("utils/proxy/http", () => ({
|
||||
httpProxy,
|
||||
}));
|
||||
|
||||
vi.mock("utils/logger", () => ({
|
||||
default: () => logger,
|
||||
}));
|
||||
|
||||
import handler from "pages/api/widgets/customapi";
|
||||
|
||||
const json = (body) => Buffer.from(JSON.stringify(body));
|
||||
|
||||
async function callRoute(options, index = "0") {
|
||||
getPrivateWidgetOptions.mockResolvedValueOnce(options);
|
||||
const res = createMockRes();
|
||||
await handler({ query: { index } }, res);
|
||||
return res;
|
||||
}
|
||||
|
||||
describe("pages/api/widgets/customapi", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it.each([
|
||||
["no widget at that index", undefined],
|
||||
["a widget without a url", { method: "GET" }],
|
||||
["an invalid url", { url: "api.local/data" }],
|
||||
])("returns 400 without calling upstream for %s", async (_, options) => {
|
||||
const res = await callRoute(options, "3");
|
||||
|
||||
expect(getPrivateWidgetOptions).toHaveBeenCalledWith("customapi", "3");
|
||||
expect(res.statusCode).toBe(400);
|
||||
expect(httpProxy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("proxies an authenticated POST with custom headers and a JSON body", async () => {
|
||||
httpProxy.mockResolvedValueOnce([200, "application/json", json({ json: { hello: "world" } })]);
|
||||
|
||||
const res = await callRoute({
|
||||
url: "https://httpbin.org/post",
|
||||
username: "admin",
|
||||
password: "hunter2",
|
||||
method: "POST",
|
||||
headers: { "X-Secret-Token": "super-secret", "Content-Type": "application/json" },
|
||||
requestBody: { hello: "world" },
|
||||
});
|
||||
|
||||
expect(httpProxy).toHaveBeenCalledWith(new URL("https://httpbin.org/post"), {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"User-Agent": "homepage",
|
||||
Accept: "application/json",
|
||||
"X-Secret-Token": "super-secret",
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Basic ${Buffer.from("admin:hunter2").toString("base64")}`,
|
||||
},
|
||||
body: '{"hello":"world"}',
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.body).toEqual({ json: { hello: "world" } });
|
||||
});
|
||||
|
||||
it("sends a string body as-is and lets config override default headers", async () => {
|
||||
httpProxy.mockResolvedValueOnce([200, "application/json", json({ data: { viewer: { login: "shamoon" } } })]);
|
||||
const query = '{"query":"{ viewer { login } }"}';
|
||||
|
||||
const res = await callRoute({
|
||||
url: "https://api.github.com/graphql",
|
||||
method: "POST",
|
||||
headers: { Authorization: "Bearer ghp_token", "User-Agent": "my-dashboard" },
|
||||
requestBody: query,
|
||||
});
|
||||
|
||||
expect(httpProxy).toHaveBeenCalledWith(expect.any(URL), {
|
||||
method: "POST",
|
||||
headers: { "User-Agent": "my-dashboard", Accept: "application/json", Authorization: "Bearer ghp_token" },
|
||||
body: query,
|
||||
});
|
||||
expect(res.body).toEqual({ data: { viewer: { login: "shamoon" } } });
|
||||
});
|
||||
|
||||
it.each([
|
||||
["an HTTP error", [403, "application/json", json({ message: "API rate limit exceeded for 1.2.3.4" })]],
|
||||
[
|
||||
"a network failure",
|
||||
[500, "application/json", { error: { message: "connect ECONNREFUSED", rawError: { address: "10.0.0.5" } } }],
|
||||
],
|
||||
["a non-JSON response", [200, "text/html", Buffer.from("<html><body>Login</body></html>")]],
|
||||
])("returns only a sanitized error for %s", async (_, upstream) => {
|
||||
httpProxy.mockResolvedValueOnce(upstream);
|
||||
|
||||
const res = await callRoute({ url: "https://api.github.com/repos/gethomepage/homepage?token=abc" });
|
||||
|
||||
expect(httpProxy).toHaveBeenCalledWith(expect.any(URL), {
|
||||
method: "GET",
|
||||
headers: { "User-Agent": "homepage", Accept: "application/json" },
|
||||
});
|
||||
expect(res.statusCode).toBe(upstream[0] === 200 ? 500 : upstream[0]);
|
||||
expect(res.body.error.url).toBe("api.github.com (see logs for details)");
|
||||
expect(JSON.stringify(res.body)).not.toMatch(/rate limit|ECONNREFUSED|10\.0\.0\.5|<html>|token=abc/);
|
||||
expect(res.setHeader).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -7,6 +7,10 @@ import { SettingsContext } from "utils/contexts/settings";
|
||||
export default function Item({ bookmark, iconOnly = false }) {
|
||||
const description = bookmark.description ?? new URL(bookmark.href).hostname;
|
||||
const { settings } = useContext(SettingsContext);
|
||||
const cardStyle =
|
||||
settings.cardStyle === "hairline"
|
||||
? "shadow-xs inset-ring inset-ring-black/5 dark:inset-ring-white/5 hover:inset-ring-black/10 dark:hover:inset-ring-white/10"
|
||||
: "shadow-md shadow-theme-900/10 dark:shadow-theme-900/20";
|
||||
|
||||
return (
|
||||
<li
|
||||
@@ -22,7 +26,8 @@ export default function Item({ bookmark, iconOnly = false }) {
|
||||
target={bookmark.target ?? settings.target ?? "_blank"}
|
||||
className={classNames(
|
||||
settings.cardBlur !== undefined && `backdrop-blur${settings.cardBlur.length ? "-" : ""}${settings.cardBlur}`,
|
||||
"text-left cursor-pointer transition-all rounded-md font-medium text-theme-700 dark:text-theme-200 dark:hover:text-theme-300 shadow-md shadow-theme-900/10 dark:shadow-theme-900/20 bg-theme-100/20 hover:bg-theme-300/20 dark:bg-white/5 dark:hover:bg-white/10",
|
||||
cardStyle,
|
||||
"text-left cursor-pointer transition-all rounded-md font-medium text-theme-700 dark:text-theme-200 dark:hover:text-theme-300 bg-theme-100/20 hover:bg-theme-300/20 dark:bg-white/5 dark:hover:bg-white/10",
|
||||
iconOnly ? "h-[60px] w-[60px] grid" : "block w-full mb-3",
|
||||
)}
|
||||
>
|
||||
|
||||
@@ -21,6 +21,16 @@ describe("components/bookmarks/item", () => {
|
||||
expect(screen.getByRole("link").getAttribute("target")).toBe("_self");
|
||||
});
|
||||
|
||||
it("applies hairline card styles when cardStyle is set", () => {
|
||||
renderWithProviders(<Item bookmark={{ name: "A", href: "http://example.com/x", abbr: "A" }} iconOnly={false} />, {
|
||||
settings: { cardStyle: "hairline" },
|
||||
});
|
||||
|
||||
const className = screen.getByRole("link").className;
|
||||
expect(className).toContain("inset-ring");
|
||||
expect(className).not.toContain("shadow-md");
|
||||
});
|
||||
|
||||
it("renders icon-only layout with icon when provided", () => {
|
||||
renderWithProviders(
|
||||
<Item bookmark={{ name: "A", href: "http://example.com/x", abbr: "A", icon: "mdi-home" }} iconOnly />,
|
||||
|
||||
@@ -19,6 +19,10 @@ export default function Item({ service, groupName, useEqualHeights }) {
|
||||
const { settings } = useContext(SettingsContext);
|
||||
const showStats = service.showStats === false ? false : settings.showStats;
|
||||
const statusStyle = service.statusStyle !== undefined ? service.statusStyle : settings.statusStyle;
|
||||
const cardStyle =
|
||||
settings.cardStyle === "hairline"
|
||||
? "shadow-xs inset-ring inset-ring-black/5 dark:inset-ring-white/5 hover:inset-ring-black/10 dark:hover:inset-ring-white/10"
|
||||
: "shadow-md shadow-theme-900/10 dark:shadow-theme-900/20";
|
||||
const [statsOpen, setStatsOpen] = useState(service.showStats);
|
||||
const [statsClosing, setStatsClosing] = useState(false);
|
||||
|
||||
@@ -39,7 +43,8 @@ export default function Item({ service, groupName, useEqualHeights }) {
|
||||
className={classNames(
|
||||
settings.cardBlur !== undefined && `backdrop-blur${settings.cardBlur.length ? "-" : ""}${settings.cardBlur}`,
|
||||
useEqualHeights && "h-[calc(100%-0.5rem)]",
|
||||
"transition-all mb-2 p-1 rounded-md font-medium text-theme-700 dark:text-theme-200 dark:hover:text-theme-300 shadow-md shadow-theme-900/10 dark:shadow-theme-900/20 bg-theme-100/20 hover:bg-theme-300/20 dark:bg-white/5 dark:hover:bg-white/10 relative overflow-clip service-card",
|
||||
cardStyle,
|
||||
"transition-all mb-2 p-1 rounded-md font-medium text-theme-700 dark:text-theme-200 dark:hover:text-theme-300 bg-theme-100/20 hover:bg-theme-300/20 dark:bg-white/5 dark:hover:bg-white/10 relative overflow-clip service-card",
|
||||
)}
|
||||
>
|
||||
<div className="flex select-none z-0 service-title">
|
||||
|
||||
@@ -4,11 +4,14 @@ import { useContext, useMemo } from "react";
|
||||
|
||||
import { BlockHighlightContext } from "./highlight-context";
|
||||
|
||||
import { SettingsContext } from "utils/contexts/settings";
|
||||
import { evaluateHighlight, getHighlightClass } from "utils/highlights";
|
||||
|
||||
export default function Block({ value, highlightValue, label, field }) {
|
||||
const { t } = useTranslation();
|
||||
const highlightConfig = useContext(BlockHighlightContext);
|
||||
const { settings } = useContext(SettingsContext);
|
||||
const refined = settings?.blockStyle === "refined";
|
||||
|
||||
const highlight = useMemo(() => {
|
||||
if (!highlightConfig) return null;
|
||||
@@ -45,9 +48,20 @@ export default function Block({ value, highlightValue, label, field }) {
|
||||
data-highlight-level={highlight?.level}
|
||||
data-highlight-source={highlight?.source}
|
||||
>
|
||||
<div className="font-thin text-sm">{value === undefined || value === null ? "-" : value}</div>
|
||||
<div
|
||||
className={classNames("font-bold text-xs uppercase", applyToValueOnly && "text-theme-700 dark:text-theme-200")}
|
||||
className={classNames(
|
||||
refined ? "text-[13px] font-medium tabular-nums" : "font-thin text-sm",
|
||||
"service-block-value",
|
||||
)}
|
||||
>
|
||||
{value === undefined || value === null ? "-" : value}
|
||||
</div>
|
||||
<div
|
||||
className={classNames(
|
||||
refined ? "text-[10px] font-semibold uppercase tracking-wider opacity-60" : "font-bold text-xs uppercase",
|
||||
applyToValueOnly && "text-theme-700 dark:text-theme-200",
|
||||
"service-block-label",
|
||||
)}
|
||||
>
|
||||
{t(label)}
|
||||
</div>
|
||||
|
||||
@@ -39,6 +39,24 @@ describe("components/services/widget/block", () => {
|
||||
expect(el.className).toContain("danger-class");
|
||||
});
|
||||
|
||||
it("uses the standard block styles by default", () => {
|
||||
const { container } = renderWithProviders(<Block label="some.label" value="1" />, { settings: {} });
|
||||
|
||||
expect(container.querySelector(".service-block-value").className).toContain("font-thin");
|
||||
expect(container.querySelector(".service-block-label").className).toContain("font-bold");
|
||||
});
|
||||
|
||||
it("applies refined block styles when blockStyle is set", () => {
|
||||
const { container } = renderWithProviders(<Block label="some.label" value="1" />, {
|
||||
settings: { blockStyle: "refined" },
|
||||
});
|
||||
|
||||
const value = container.querySelector(".service-block-value");
|
||||
expect(value.className).toContain("tabular-nums");
|
||||
expect(value.className).not.toContain("font-thin");
|
||||
expect(container.querySelector(".service-block-label").className).toContain("tracking-wider");
|
||||
});
|
||||
|
||||
it("prefers highlightValue over the rendered value for numeric highlighting", () => {
|
||||
const highlightConfig = {
|
||||
levels: { warn: "warn-class" },
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import classNames from "classnames";
|
||||
import { useTranslation } from "next-i18next/pages";
|
||||
import { TbApi } from "react-icons/tb";
|
||||
import useSWR from "swr";
|
||||
|
||||
import Container from "../widget/container";
|
||||
import Error from "../widget/error";
|
||||
import Raw from "../widget/raw";
|
||||
import WidgetLabel from "../widget/widget_label";
|
||||
|
||||
import ResolvedIcon from "components/resolvedicon";
|
||||
import { formatValue, getValue } from "widgets/customapi/utils";
|
||||
|
||||
export default function CustomApi({ options }) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const { index, icon, label, mappings = [], refreshInterval = 10000 } = options;
|
||||
|
||||
const { data, error } = useSWR(`/api/widgets/customapi?${new URLSearchParams({ index }).toString()}`, {
|
||||
refreshInterval: Math.max(1000, refreshInterval),
|
||||
});
|
||||
|
||||
if (error || (data?.error && !mappings.some((mapping) => mapping.field === "error"))) {
|
||||
return <Error options={options} />;
|
||||
}
|
||||
|
||||
return (
|
||||
<Container options={options} additionalClassNames="information-widget-customapi">
|
||||
<Raw>
|
||||
<div className="flex flex-row items-center">
|
||||
<div className="flex-none mr-2">
|
||||
{icon ? (
|
||||
<ResolvedIcon icon={icon} width={24} height={24} />
|
||||
) : (
|
||||
<TbApi className="w-6 h-6 text-theme-800 dark:text-theme-200" />
|
||||
)}
|
||||
</div>
|
||||
<div className={classNames("flex flex-wrap items-center gap-0.5", !data && "animate-pulse")}>
|
||||
{mappings.map((mapping) => (
|
||||
<div key={mapping.label} className="flex flex-col items-center justify-center px-1 text-xs">
|
||||
<span className="text-theme-800 dark:text-theme-200">{mapping.label}</span>
|
||||
<span className="text-theme-800/70 dark:text-theme-200/50">
|
||||
{data ? formatValue(t, mapping, getValue(mapping.field, data)) : "-"}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
{label && <WidgetLabel label={label} />}
|
||||
</Raw>
|
||||
</Container>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { screen } from "@testing-library/react";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { renderWithProviders } from "test-utils/render-with-providers";
|
||||
|
||||
const { useSWR } = vi.hoisted(() => ({ useSWR: vi.fn() }));
|
||||
vi.mock("swr", () => ({ default: useSWR }));
|
||||
|
||||
vi.mock("components/resolvedicon", () => ({
|
||||
default: ({ icon }) => <div data-testid="resolved-icon" data-icon={icon} />,
|
||||
}));
|
||||
|
||||
import CustomApi from "./customapi";
|
||||
|
||||
const settings = { settings: { target: "_self" } };
|
||||
|
||||
describe("components/widgets/customapi", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("shows GitHub repo stats once loaded, with the fallback icon and a label", () => {
|
||||
const options = {
|
||||
index: 6,
|
||||
label: "Homepage",
|
||||
refreshInterval: 300000,
|
||||
mappings: [
|
||||
{ field: "stargazers_count", label: "Stars", format: "number" },
|
||||
{ field: "open_issues_count", label: "Open", format: "number" },
|
||||
{ field: "forks_count", label: "Forks", format: "number" },
|
||||
],
|
||||
};
|
||||
|
||||
useSWR.mockReturnValue({ data: undefined, error: undefined });
|
||||
const { container, rerender } = renderWithProviders(<CustomApi options={options} />, settings);
|
||||
|
||||
expect(useSWR).toHaveBeenCalledWith("/api/widgets/customapi?index=6", { refreshInterval: 300000 });
|
||||
expect(screen.getAllByText("-")).toHaveLength(3);
|
||||
expect(screen.queryByTestId("resolved-icon")).toBeNull();
|
||||
expect(container.querySelector("svg")).not.toBeNull();
|
||||
|
||||
useSWR.mockReturnValue({
|
||||
data: { stargazers_count: 32809, open_issues_count: 1, forks_count: 2127, owner: { login: "gethomepage" } },
|
||||
error: undefined,
|
||||
});
|
||||
rerender(<CustomApi options={options} />);
|
||||
|
||||
expect(screen.queryByText("-")).toBeNull();
|
||||
expect(screen.getByText("Stars").nextSibling).toHaveTextContent("32809");
|
||||
expect(screen.getByText("Open").nextSibling).toHaveTextContent("1");
|
||||
expect(screen.getByText("Forks").nextSibling).toHaveTextContent("2127");
|
||||
expect(screen.getByText("Homepage")).toHaveClass("information-widget-label");
|
||||
});
|
||||
|
||||
it("shows a nested weather value with a configured icon and suffix", () => {
|
||||
useSWR.mockReturnValue({
|
||||
data: { current: { time: "2026-09-22T20:15", temperature_2m: 7.8, wind_speed_10m: 12.4 } },
|
||||
error: undefined,
|
||||
});
|
||||
|
||||
renderWithProviders(
|
||||
<CustomApi
|
||||
options={{
|
||||
index: 7,
|
||||
icon: "mdi-thermometer",
|
||||
mappings: [{ field: "current.temperature_2m", label: "Temp", format: "float", suffix: "°C" }],
|
||||
}}
|
||||
/>,
|
||||
settings,
|
||||
);
|
||||
|
||||
expect(useSWR).toHaveBeenCalledWith("/api/widgets/customapi?index=7", { refreshInterval: 10000 });
|
||||
expect(screen.getByTestId("resolved-icon")).toHaveAttribute("data-icon", "mdi-thermometer");
|
||||
expect(screen.getByText("7.8 °C")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows a status API's error field as data when it is mapped", () => {
|
||||
useSWR.mockReturnValue({ data: { error: "E_NONE", pending: 3 }, error: undefined });
|
||||
|
||||
renderWithProviders(
|
||||
<CustomApi
|
||||
options={{
|
||||
index: 0,
|
||||
mappings: [
|
||||
{ field: "error", label: "Status", remap: [{ value: "E_NONE", to: "OK" }] },
|
||||
{ field: "pending", label: "Queue", format: "number" },
|
||||
],
|
||||
}}
|
||||
/>,
|
||||
settings,
|
||||
);
|
||||
|
||||
expect(screen.queryByText("widget.api_error")).toBeNull();
|
||||
expect(screen.getByText("OK")).toBeInTheDocument();
|
||||
expect(screen.getByText("3")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows the error state when the upstream API fails, clamping a too-fast refresh", () => {
|
||||
useSWR.mockReturnValue({
|
||||
data: { error: { message: "HTTP Error", url: "api.github.com (see logs for details)" } },
|
||||
error: undefined,
|
||||
});
|
||||
|
||||
renderWithProviders(
|
||||
<CustomApi
|
||||
options={{ index: 6, refreshInterval: 500, mappings: [{ field: "stargazers_count", label: "Stars" }] }}
|
||||
/>,
|
||||
settings,
|
||||
);
|
||||
|
||||
expect(useSWR).toHaveBeenCalledWith("/api/widgets/customapi?index=6", { refreshInterval: 1000 });
|
||||
expect(screen.getByText("widget.api_error")).toBeInTheDocument();
|
||||
expect(screen.queryByText("Stars")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -16,6 +16,7 @@ const widgetMappings = {
|
||||
longhorn: dynamic(() => import("components/widgets/longhorn/longhorn")),
|
||||
kubernetes: dynamic(() => import("components/widgets/kubernetes/kubernetes")),
|
||||
stocks: dynamic(() => import("components/widgets/stocks/stocks")),
|
||||
customapi: dynamic(() => import("components/widgets/customapi/customapi")),
|
||||
};
|
||||
|
||||
export default function Widget({ widget, style }) {
|
||||
|
||||
@@ -25,12 +25,12 @@ export default function Resource({
|
||||
}`}
|
||||
>
|
||||
<div className="text-theme-800 dark:text-theme-200 text-xs flex flex-row justify-between gap-2">
|
||||
<div className="pl-0.5">{value}</div>
|
||||
<div className="pl-0.5 resource-value">{value}</div>
|
||||
<div className="pr-1">{label}</div>
|
||||
</div>
|
||||
{expanded && (
|
||||
<div className="text-theme-800 dark:text-theme-200 text-xs flex flex-row justify-between gap-2">
|
||||
<div className="pl-0.5">{expandedValue}</div>
|
||||
<div className="pl-0.5 resource-value">{expandedValue}</div>
|
||||
<div className="pr-1">{expandedLabel}</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -3,6 +3,7 @@ import { appWithTranslation } from "next-i18next/pages";
|
||||
import Head from "next/head";
|
||||
import "styles/globals.css";
|
||||
import "styles/manrope.css";
|
||||
import "styles/plex-mono.css";
|
||||
import "styles/theme.css";
|
||||
import { SWRConfig } from "swr";
|
||||
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
import { getPrivateWidgetOptions } from "utils/config/widget-helpers";
|
||||
import createLogger from "utils/logger";
|
||||
import { sanitizeErrorURL } from "utils/proxy/api-helpers";
|
||||
import { httpProxy } from "utils/proxy/http";
|
||||
|
||||
const logger = createLogger("customapi");
|
||||
|
||||
export default async function handler(req, res) {
|
||||
const { index } = req.query;
|
||||
|
||||
const options = await getPrivateWidgetOptions("customapi", index);
|
||||
|
||||
if (!options?.url) {
|
||||
return res.status(400).json({ error: "Missing Custom API URL" });
|
||||
}
|
||||
|
||||
let url;
|
||||
try {
|
||||
url = new URL(options.url);
|
||||
} catch {
|
||||
return res.status(400).json({ error: "Invalid Custom API URL" });
|
||||
}
|
||||
|
||||
const headers = { "User-Agent": "homepage", Accept: "application/json", ...(options.headers ?? {}) };
|
||||
if (options.username && options.password) {
|
||||
headers.Authorization = `Basic ${Buffer.from(`${options.username}:${options.password}`).toString("base64")}`;
|
||||
}
|
||||
|
||||
const params = { method: options.method ?? "GET", headers };
|
||||
if (options.requestBody) {
|
||||
params.body = typeof options.requestBody === "object" ? JSON.stringify(options.requestBody) : options.requestBody;
|
||||
}
|
||||
|
||||
const [status, , data] = await httpProxy(url, params);
|
||||
|
||||
if (status >= 400) {
|
||||
logger.debug("HTTP Error %d calling %s//%s%s", status, url.protocol, url.host, url.pathname);
|
||||
return res.status(status).json({ error: { message: "HTTP Error", url: sanitizeErrorURL(url) } });
|
||||
}
|
||||
|
||||
try {
|
||||
return res.status(status).json(JSON.parse(Buffer.from(data).toString()));
|
||||
} catch {
|
||||
return res.status(500).json({ error: { message: "Invalid JSON", url: sanitizeErrorURL(url) } });
|
||||
}
|
||||
}
|
||||
+4
-2
@@ -552,7 +552,9 @@ export default function Wrapper({ initialSettings, fallback }) {
|
||||
const html = document.documentElement;
|
||||
const body = document.body;
|
||||
|
||||
html.classList.remove("dark", "scheme-dark", "scheme-light");
|
||||
html.classList.remove("dark", "scheme-dark", "scheme-light", "font-plex", "font-plex-data");
|
||||
if (initialSettings.font === "plex") html.classList.add("font-plex");
|
||||
if (initialSettings.font === "plexData") html.classList.add("font-plex-data");
|
||||
html.classList.toggle("dark", theme === "dark");
|
||||
html.classList.add(theme === "dark" ? "scheme-dark" : "scheme-light");
|
||||
|
||||
@@ -571,7 +573,7 @@ export default function Wrapper({ initialSettings, fallback }) {
|
||||
body.style.backgroundImage = "";
|
||||
body.style.backgroundColor = "";
|
||||
body.style.backgroundAttachment = "";
|
||||
}, [backgroundImage, opacity, theme, color, initialSettings.color]);
|
||||
}, [backgroundImage, opacity, theme, color, initialSettings.color, initialSettings.font]);
|
||||
|
||||
return (
|
||||
<>
|
||||
|
||||
Binary file not shown.
@@ -0,0 +1,93 @@
|
||||
Copyright © 2017 IBM Corp. with Reserved Font Name "Plex"
|
||||
|
||||
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||
|
||||
This license is copied below, and is also available with a FAQ at: http://scripts.sil.org/OFL
|
||||
|
||||
|
||||
-----------------------------------------------------------
|
||||
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||
-----------------------------------------------------------
|
||||
|
||||
PREAMBLE
|
||||
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||
development of collaborative font projects, to support the font creation
|
||||
efforts of academic and linguistic communities, and to provide a free and
|
||||
open framework in which fonts may be shared and improved in partnership
|
||||
with others.
|
||||
|
||||
The OFL allows the licensed fonts to be used, studied, modified and
|
||||
redistributed freely as long as they are not sold by themselves. The
|
||||
fonts, including any derivative works, can be bundled, embedded,
|
||||
redistributed and/or sold with any software provided that any reserved
|
||||
names are not used by derivative works. The fonts and derivatives,
|
||||
however, cannot be released under any other type of license. The
|
||||
requirement for fonts to remain under this license does not apply
|
||||
to any document created using the fonts or their derivatives.
|
||||
|
||||
DEFINITIONS
|
||||
"Font Software" refers to the set of files released by the Copyright
|
||||
Holder(s) under this license and clearly marked as such. This may
|
||||
include source files, build scripts and documentation.
|
||||
|
||||
"Reserved Font Name" refers to any names specified as such after the
|
||||
copyright statement(s).
|
||||
|
||||
"Original Version" refers to the collection of Font Software components as
|
||||
distributed by the Copyright Holder(s).
|
||||
|
||||
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||
or substituting -- in part or in whole -- any of the components of the
|
||||
Original Version, by changing formats or by porting the Font Software to a
|
||||
new environment.
|
||||
|
||||
"Author" refers to any designer, engineer, programmer, technical
|
||||
writer or other person who contributed to the Font Software.
|
||||
|
||||
PERMISSION & CONDITIONS
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||
redistribute, and sell modified and unmodified copies of the Font
|
||||
Software, subject to the following conditions:
|
||||
|
||||
1) Neither the Font Software nor any of its individual components,
|
||||
in Original or Modified Versions, may be sold by itself.
|
||||
|
||||
2) Original or Modified Versions of the Font Software may be bundled,
|
||||
redistributed and/or sold with any software, provided that each copy
|
||||
contains the above copyright notice and this license. These can be
|
||||
included either as stand-alone text files, human-readable headers or
|
||||
in the appropriate machine-readable metadata fields within text or
|
||||
binary files as long as those fields can be easily viewed by the user.
|
||||
|
||||
3) No Modified Version of the Font Software may use the Reserved Font
|
||||
Name(s) unless explicit written permission is granted by the corresponding
|
||||
Copyright Holder. This restriction only applies to the primary font name as
|
||||
presented to the users.
|
||||
|
||||
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||
Software shall not be used to promote, endorse or advertise any
|
||||
Modified Version, except to acknowledge the contribution(s) of the
|
||||
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||
permission.
|
||||
|
||||
5) The Font Software, modified or unmodified, in part or in whole,
|
||||
must be distributed entirely under this license, and must not be
|
||||
distributed under any other license. The requirement for fonts to
|
||||
remain under this license does not apply to any document created
|
||||
using the Font Software.
|
||||
|
||||
TERMINATION
|
||||
This license becomes null and void if any of the above conditions are
|
||||
not met.
|
||||
|
||||
DISCLAIMER
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,56 @@
|
||||
@font-face {
|
||||
font-family: "IBM Plex Mono";
|
||||
font-weight: 400;
|
||||
font-style: normal;
|
||||
src:
|
||||
local("IBM Plex Mono"),
|
||||
url("./font/IBMPlexMono-Regular.woff2") format("woff2");
|
||||
font-display: swap;
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "IBM Plex Mono";
|
||||
font-weight: 500;
|
||||
font-style: normal;
|
||||
src:
|
||||
local("IBM Plex Mono Medium"),
|
||||
url("./font/IBMPlexMono-Medium.woff2") format("woff2");
|
||||
font-display: swap;
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "IBM Plex Mono";
|
||||
font-weight: 600;
|
||||
font-style: normal;
|
||||
src:
|
||||
local("IBM Plex Mono SemiBold"),
|
||||
url("./font/IBMPlexMono-SemiBold.woff2") format("woff2");
|
||||
font-display: swap;
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "IBM Plex Mono";
|
||||
font-weight: 700;
|
||||
font-style: normal;
|
||||
src:
|
||||
local("IBM Plex Mono Bold"),
|
||||
url("./font/IBMPlexMono-Bold.woff2") format("woff2");
|
||||
font-display: swap;
|
||||
}
|
||||
|
||||
/* font-size-adjust keeps mono from reading larger than Manrope at the same size */
|
||||
.font-plex,
|
||||
.font-plex body {
|
||||
font-family: "IBM Plex Mono", ui-monospace, SFMono-Regular, Menlo, monospace;
|
||||
font-size-adjust: 0.5;
|
||||
letter-spacing: -0.01em;
|
||||
}
|
||||
|
||||
.font-plex-data .service-block-value,
|
||||
.font-plex-data .service-tags,
|
||||
.font-plex-data .tabular-nums,
|
||||
.font-plex-data .information-widget-resource .resource-value,
|
||||
.font-plex-data .service-container {
|
||||
font-family: "IBM Plex Mono", ui-monospace, SFMono-Regular, Menlo, monospace;
|
||||
font-size-adjust: 0.5;
|
||||
}
|
||||
@@ -9,5 +9,7 @@ export function renderWithProviders(ui, { settings = {} } = {}) {
|
||||
setSettings: () => {},
|
||||
};
|
||||
|
||||
return render(<SettingsContext.Provider value={value}>{ui}</SettingsContext.Provider>);
|
||||
const wrapper = ({ children }) => <SettingsContext.Provider value={value}>{children}</SettingsContext.Provider>;
|
||||
|
||||
return render(ui, { wrapper });
|
||||
}
|
||||
|
||||
@@ -353,6 +353,9 @@ export function cleanServiceGroups(groups) {
|
||||
expandOneStreamToTwoRows,
|
||||
showEpisodeNumber,
|
||||
|
||||
// feed
|
||||
layout,
|
||||
|
||||
// frigate
|
||||
enableRecentEvents,
|
||||
|
||||
@@ -675,6 +678,9 @@ export function cleanServiceGroups(groups) {
|
||||
if (showTime) widget.showTime = showTime;
|
||||
if (timezone) widget.timezone = timezone;
|
||||
}
|
||||
if (type === "feed") {
|
||||
if (layout) widget.layout = layout;
|
||||
}
|
||||
if (type === "dockhand") {
|
||||
if (environment) widget.environment = environment;
|
||||
}
|
||||
|
||||
@@ -31,7 +31,7 @@ export async function cleanWidgetGroups(widgets) {
|
||||
const optionKeys = Object.keys(sanitizedOptions);
|
||||
|
||||
// delete private options from the sanitized options
|
||||
["username", "password", "key", "apiKey"].forEach((pO) => {
|
||||
["username", "password", "key", "apiKey", "headers", "requestBody", "method"].forEach((pO) => {
|
||||
if (optionKeys.includes(pO)) {
|
||||
delete sanitizedOptions[pO];
|
||||
}
|
||||
@@ -57,7 +57,7 @@ export async function getPrivateWidgetOptions(type, widgetIndex) {
|
||||
|
||||
const privateOptions =
|
||||
widgets.map((widget) => {
|
||||
const { index, url, username, password, key, apiKey } = widget.options;
|
||||
const { index, url, username, password, key, apiKey, headers, requestBody, method } = widget.options;
|
||||
|
||||
return {
|
||||
type: widget.type,
|
||||
@@ -68,6 +68,9 @@ export async function getPrivateWidgetOptions(type, widgetIndex) {
|
||||
password,
|
||||
key,
|
||||
apiKey,
|
||||
headers,
|
||||
requestBody,
|
||||
method,
|
||||
},
|
||||
};
|
||||
}) || {};
|
||||
|
||||
@@ -60,6 +60,17 @@ describe("utils/config/widget-helpers", () => {
|
||||
expect(cleaned[2].options.apiKey).toBeUndefined();
|
||||
});
|
||||
|
||||
it("cleanWidgetGroups removes customapi request options", async () => {
|
||||
const cleaned = await cleanWidgetGroups([
|
||||
{
|
||||
type: "customapi",
|
||||
options: { index: 0, url: "http://x", headers: { a: "b" }, requestBody: "body", method: "POST", icon: "mdi-x" },
|
||||
},
|
||||
]);
|
||||
|
||||
expect(cleaned[0].options).toEqual({ index: 0, icon: "mdi-x" });
|
||||
});
|
||||
|
||||
it("getPrivateWidgetOptions returns private options for a specific widget", async () => {
|
||||
fs.readFile.mockResolvedValueOnce("ignored");
|
||||
yaml.load.mockReturnValueOnce([{ search: { url: "http://x", username: "u", password: "p", key: "k" } }]);
|
||||
|
||||
@@ -37,6 +37,7 @@ const components = {
|
||||
emby: dynamic(() => import("./emby/component")),
|
||||
esphome: dynamic(() => import("./esphome/component")),
|
||||
evcc: dynamic(() => import("./evcc/component")),
|
||||
feed: dynamic(() => import("./feed/component")),
|
||||
filebrowser: dynamic(() => import("./filebrowser/component")),
|
||||
fileflows: dynamic(() => import("./fileflows/component")),
|
||||
firefly: dynamic(() => import("./firefly/component")),
|
||||
|
||||
@@ -1,161 +1,13 @@
|
||||
import classNames from "classnames";
|
||||
import { useTranslation } from "next-i18next/pages";
|
||||
|
||||
import { formatValue, getColor, getValue } from "./utils";
|
||||
|
||||
import Block from "components/services/widget/block";
|
||||
import Container from "components/services/widget/container";
|
||||
import * as shvl from "utils/config/shvl";
|
||||
import useWidgetAPI from "utils/proxy/use-widget-api";
|
||||
|
||||
function getValue(field, data) {
|
||||
let value = data;
|
||||
let lastField = field;
|
||||
let key = "";
|
||||
|
||||
// Support APIs that return arrays or scalars directly.
|
||||
if (typeof field === "undefined") {
|
||||
return value;
|
||||
}
|
||||
|
||||
// shvl is easier, everything else is kept for backwards compatibility.
|
||||
if (typeof field === "string") {
|
||||
return shvl.get(data, field, null) ?? data[field] ?? null;
|
||||
}
|
||||
|
||||
while (typeof lastField === "object") {
|
||||
key = Object.keys(lastField)[0] ?? null;
|
||||
|
||||
if (key === null) {
|
||||
break;
|
||||
}
|
||||
|
||||
value = value[key];
|
||||
lastField = lastField[key];
|
||||
}
|
||||
|
||||
if (typeof value === "undefined") {
|
||||
return null;
|
||||
}
|
||||
|
||||
return value[lastField] ?? null;
|
||||
}
|
||||
|
||||
function getSize(data) {
|
||||
if (Array.isArray(data) || typeof data === "string") {
|
||||
return data.length;
|
||||
} else if (typeof data === "object" && data !== null) {
|
||||
return Object.keys(data).length;
|
||||
}
|
||||
|
||||
return NaN;
|
||||
}
|
||||
|
||||
function formatValue(t, mapping, rawValue) {
|
||||
let value = rawValue;
|
||||
|
||||
// Remap the value.
|
||||
const remaps = mapping?.remap ?? [];
|
||||
for (let i = 0; i < remaps.length; i += 1) {
|
||||
const remap = remaps[i];
|
||||
if (remap?.any || remap?.value === value) {
|
||||
value = remap.to;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Scale the value. Accepts either a number to multiply by or a string
|
||||
// like "12/345".
|
||||
const scale = mapping?.scale;
|
||||
if (typeof scale === "number") {
|
||||
value *= scale;
|
||||
} else if (typeof scale === "string") {
|
||||
const parts = scale.split("/");
|
||||
const numerator = parts[0] ? parseFloat(parts[0]) : 1;
|
||||
const denominator = parts[1] ? parseFloat(parts[1]) : 1;
|
||||
value = (value * numerator) / denominator;
|
||||
}
|
||||
|
||||
// Format the value using a known type.
|
||||
switch (mapping?.format) {
|
||||
case "number":
|
||||
value = t("common.number", { value: parseInt(value, 10) });
|
||||
break;
|
||||
case "float":
|
||||
value = t("common.number", { value });
|
||||
break;
|
||||
case "percent":
|
||||
value = t("common.percent", { value });
|
||||
break;
|
||||
case "duration":
|
||||
value = t("common.duration", { value });
|
||||
break;
|
||||
case "bytes":
|
||||
value = t("common.bytes", { value });
|
||||
break;
|
||||
case "bitrate":
|
||||
value = t("common.bitrate", { value });
|
||||
break;
|
||||
case "date":
|
||||
value = t("common.date", {
|
||||
value,
|
||||
lng: mapping?.locale,
|
||||
dateStyle: mapping?.dateStyle ?? "long",
|
||||
timeStyle: mapping?.timeStyle,
|
||||
});
|
||||
break;
|
||||
case "relativeDate":
|
||||
value = t("common.relativeDate", {
|
||||
value,
|
||||
lng: mapping?.locale,
|
||||
style: mapping?.style,
|
||||
numeric: mapping?.numeric,
|
||||
});
|
||||
break;
|
||||
case "size":
|
||||
value = t("common.number", { value: getSize(value) });
|
||||
break;
|
||||
case "text":
|
||||
default:
|
||||
// nothing
|
||||
}
|
||||
|
||||
// Apply fixed prefix.
|
||||
const prefix = mapping?.prefix;
|
||||
if (prefix) {
|
||||
value = `${prefix} ${value}`;
|
||||
}
|
||||
|
||||
// Apply fixed suffix.
|
||||
const suffix = mapping?.suffix;
|
||||
if (suffix) {
|
||||
value = `${value} ${suffix}`;
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
function getColor(mapping, customData) {
|
||||
const value = getValue(mapping.additionalField.field, customData);
|
||||
const { color } = mapping.additionalField;
|
||||
|
||||
switch (color) {
|
||||
case "adaptive":
|
||||
try {
|
||||
const number = parseFloat(value);
|
||||
return number > 0 ? "text-emerald-300" : "text-rose-300";
|
||||
} catch (e) {
|
||||
return "";
|
||||
}
|
||||
case "black":
|
||||
return `text-black`;
|
||||
case "white":
|
||||
return `text-white`;
|
||||
case "theme":
|
||||
return `text-theme-500`;
|
||||
default:
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
export default function Component({ service }) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
import * as shvl from "utils/config/shvl";
|
||||
|
||||
export function getValue(field, data) {
|
||||
let value = data;
|
||||
let lastField = field;
|
||||
let key = "";
|
||||
|
||||
// Support APIs that return arrays or scalars directly.
|
||||
if (typeof field === "undefined") {
|
||||
return value;
|
||||
}
|
||||
|
||||
// shvl is easier, everything else is kept for backwards compatibility.
|
||||
if (typeof field === "string") {
|
||||
return shvl.get(data, field, null) ?? data[field] ?? null;
|
||||
}
|
||||
|
||||
while (typeof lastField === "object") {
|
||||
key = Object.keys(lastField)[0] ?? null;
|
||||
|
||||
if (key === null) {
|
||||
break;
|
||||
}
|
||||
|
||||
value = value[key];
|
||||
lastField = lastField[key];
|
||||
}
|
||||
|
||||
if (typeof value === "undefined") {
|
||||
return null;
|
||||
}
|
||||
|
||||
return value[lastField] ?? null;
|
||||
}
|
||||
|
||||
export function getSize(data) {
|
||||
if (Array.isArray(data) || typeof data === "string") {
|
||||
return data.length;
|
||||
} else if (typeof data === "object" && data !== null) {
|
||||
return Object.keys(data).length;
|
||||
}
|
||||
|
||||
return NaN;
|
||||
}
|
||||
|
||||
export function formatValue(t, mapping, rawValue) {
|
||||
let value = rawValue;
|
||||
|
||||
// Remap the value.
|
||||
const remaps = mapping?.remap ?? [];
|
||||
for (let i = 0; i < remaps.length; i += 1) {
|
||||
const remap = remaps[i];
|
||||
if (remap?.any || remap?.value === value) {
|
||||
value = remap.to;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Scale the value. Accepts either a number to multiply by or a string
|
||||
// like "12/345".
|
||||
const scale = mapping?.scale;
|
||||
if (typeof scale === "number") {
|
||||
value *= scale;
|
||||
} else if (typeof scale === "string") {
|
||||
const parts = scale.split("/");
|
||||
const numerator = parts[0] ? parseFloat(parts[0]) : 1;
|
||||
const denominator = parts[1] ? parseFloat(parts[1]) : 1;
|
||||
value = (value * numerator) / denominator;
|
||||
}
|
||||
|
||||
// Format the value using a known type.
|
||||
switch (mapping?.format) {
|
||||
case "number":
|
||||
value = t("common.number", { value: parseInt(value, 10) });
|
||||
break;
|
||||
case "float":
|
||||
value = t("common.number", { value });
|
||||
break;
|
||||
case "percent":
|
||||
value = t("common.percent", { value });
|
||||
break;
|
||||
case "duration":
|
||||
value = t("common.duration", { value });
|
||||
break;
|
||||
case "bytes":
|
||||
value = t("common.bytes", { value });
|
||||
break;
|
||||
case "bitrate":
|
||||
value = t("common.bitrate", { value });
|
||||
break;
|
||||
case "date":
|
||||
value = t("common.date", {
|
||||
value,
|
||||
lng: mapping?.locale,
|
||||
dateStyle: mapping?.dateStyle ?? "long",
|
||||
timeStyle: mapping?.timeStyle,
|
||||
});
|
||||
break;
|
||||
case "relativeDate":
|
||||
value = t("common.relativeDate", {
|
||||
value,
|
||||
lng: mapping?.locale,
|
||||
style: mapping?.style,
|
||||
numeric: mapping?.numeric,
|
||||
});
|
||||
break;
|
||||
case "size":
|
||||
value = t("common.number", { value: getSize(value) });
|
||||
break;
|
||||
case "text":
|
||||
default:
|
||||
// nothing
|
||||
}
|
||||
|
||||
// Apply fixed prefix.
|
||||
const prefix = mapping?.prefix;
|
||||
if (prefix) {
|
||||
value = `${prefix} ${value}`;
|
||||
}
|
||||
|
||||
// Apply fixed suffix.
|
||||
const suffix = mapping?.suffix;
|
||||
if (suffix) {
|
||||
value = `${value} ${suffix}`;
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
export function getColor(mapping, customData) {
|
||||
const value = getValue(mapping.additionalField.field, customData);
|
||||
const { color } = mapping.additionalField;
|
||||
|
||||
switch (color) {
|
||||
case "adaptive":
|
||||
try {
|
||||
const number = parseFloat(value);
|
||||
return number > 0 ? "text-emerald-300" : "text-rose-300";
|
||||
} catch (e) {
|
||||
return "";
|
||||
}
|
||||
case "black":
|
||||
return `text-black`;
|
||||
case "white":
|
||||
return `text-white`;
|
||||
case "theme":
|
||||
return `text-theme-500`;
|
||||
default:
|
||||
return "";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { formatValue, getColor, getSize, getValue } from "./utils";
|
||||
|
||||
const t = (key, { value }) => `${key.replace("common.", "")}:${value}`;
|
||||
|
||||
const data = {
|
||||
status: "online",
|
||||
stats: { cpu: 12.5, change: -1.2, users: ["a", "b"] },
|
||||
"dotted.key": 7,
|
||||
};
|
||||
|
||||
describe("widgets/customapi/utils", () => {
|
||||
it.each([
|
||||
["the root when no field is set", undefined, data],
|
||||
["a dotted path", "stats.cpu", 12.5],
|
||||
["a literal key containing a dot", "dotted.key", 7],
|
||||
["null for a missing path", "stats.missing", null],
|
||||
["a legacy object path", { stats: "cpu" }, 12.5],
|
||||
["null for a legacy path through a missing key", { missing: "cpu" }, null],
|
||||
["null for an empty legacy path", {}, null],
|
||||
])("getValue returns %s", (_, field, expected) => {
|
||||
expect(getValue(field, data)).toEqual(expected);
|
||||
});
|
||||
|
||||
it.each([
|
||||
[["a", "b", "c"], 3],
|
||||
["abcd", 4],
|
||||
[{ a: 1, b: 2 }, 2],
|
||||
[null, NaN],
|
||||
[5, NaN],
|
||||
])("getSize(%j) is %s", (input, expected) => {
|
||||
expect(getSize(input)).toEqual(expected);
|
||||
});
|
||||
|
||||
it.each([
|
||||
[{}, "raw", "raw"],
|
||||
[{ format: "number" }, "42.9", "number:42"],
|
||||
[{ format: "float" }, 4.2, "number:4.2"],
|
||||
[{ format: "percent", scale: 100 }, 0.25, "percent:25"],
|
||||
[{ format: "duration" }, 90, "duration:90"],
|
||||
[{ format: "bytes", scale: "1024/1" }, 2, "bytes:2048"],
|
||||
[{ format: "bitrate", scale: "/8" }, 800, "bitrate:100"],
|
||||
[{ format: "date" }, "2026-09-22", "date:2026-09-22"],
|
||||
[{ format: "relativeDate" }, "2026-09-22", "relativeDate:2026-09-22"],
|
||||
[{ format: "size" }, ["a", "b"], "number:2"],
|
||||
[
|
||||
{
|
||||
remap: [
|
||||
{ value: 0, to: "Off" },
|
||||
{ value: 1, to: "On" },
|
||||
],
|
||||
},
|
||||
1,
|
||||
"On",
|
||||
],
|
||||
[
|
||||
{
|
||||
remap: [
|
||||
{ value: "ok", to: "Healthy" },
|
||||
{ any: true, to: "Unknown" },
|
||||
],
|
||||
},
|
||||
"degraded",
|
||||
"Unknown",
|
||||
],
|
||||
[{ format: "number", prefix: "$", suffix: "USD" }, 10, "$ number:10 USD"],
|
||||
])("formatValue with %j formats %j as %j", (mapping, raw, expected) => {
|
||||
expect(formatValue(t, mapping, raw)).toBe(expected);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["adaptive", "stats.cpu", "text-emerald-300"],
|
||||
["adaptive", "stats.change", "text-rose-300"],
|
||||
["black", "stats.cpu", "text-black"],
|
||||
["white", "stats.cpu", "text-white"],
|
||||
["theme", "stats.cpu", "text-theme-500"],
|
||||
[undefined, "stats.cpu", ""],
|
||||
])("getColor %s for %s is %j", (color, field, expected) => {
|
||||
expect(getColor({ additionalField: { field, color } }, data)).toBe(expected);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,125 @@
|
||||
/* eslint-disable @next/next/no-img-element */
|
||||
import classNames from "classnames";
|
||||
import { useTranslation } from "next-i18next/pages";
|
||||
import { useContext } from "react";
|
||||
|
||||
import Container from "components/services/widget/container";
|
||||
import { SettingsContext } from "utils/contexts/settings";
|
||||
import useWidgetAPI from "utils/proxy/use-widget-api";
|
||||
|
||||
const rowClassName = "rounded-md bg-theme-200/50 dark:bg-theme-900/20 text-theme-700 dark:text-theme-200 text-xs";
|
||||
const hideBrokenImage = (e) => {
|
||||
e.currentTarget.style.visibility = "hidden";
|
||||
};
|
||||
|
||||
function FeedLink({ item, target, className, children }) {
|
||||
if (!item.link) return <div className={className}>{children}</div>;
|
||||
return (
|
||||
<a
|
||||
href={item.link}
|
||||
target={target}
|
||||
rel="noopener noreferrer"
|
||||
className={classNames(className, "hover:bg-theme-300/50 dark:hover:bg-theme-800/20")}
|
||||
>
|
||||
{children}
|
||||
</a>
|
||||
);
|
||||
}
|
||||
|
||||
function RelativeDate({ date }) {
|
||||
const { t } = useTranslation();
|
||||
if (!date) return null;
|
||||
return (
|
||||
<span className="shrink-0 text-theme-500 dark:text-theme-400">
|
||||
{t("common.relativeDate", { value: date, formatParams: { value: { style: "narrow", numeric: "auto" } } })}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function ListItem({ item, target }) {
|
||||
return (
|
||||
<FeedLink
|
||||
item={item}
|
||||
target={target}
|
||||
className={classNames(rowClassName, "flex items-center gap-2 px-2", item.image ? "py-1" : "h-5")}
|
||||
>
|
||||
{item.image && (
|
||||
<img
|
||||
src={item.image}
|
||||
alt=""
|
||||
loading="lazy"
|
||||
decoding="async"
|
||||
referrerPolicy="no-referrer"
|
||||
onError={hideBrokenImage}
|
||||
className="w-12 h-8 shrink-0 rounded-sm object-cover"
|
||||
/>
|
||||
)}
|
||||
<span className="grow truncate text-left">{item.title}</span>
|
||||
<RelativeDate date={item.date} />
|
||||
</FeedLink>
|
||||
);
|
||||
}
|
||||
|
||||
function GridItem({ item, target }) {
|
||||
return (
|
||||
<FeedLink item={item} target={target} className={classNames(rowClassName, "flex flex-col overflow-hidden")}>
|
||||
<div className="relative aspect-video w-full overflow-hidden bg-theme-200/50 dark:bg-theme-900/30">
|
||||
{item.image && (
|
||||
<img
|
||||
src={item.image}
|
||||
alt=""
|
||||
loading="lazy"
|
||||
decoding="async"
|
||||
referrerPolicy="no-referrer"
|
||||
onError={hideBrokenImage}
|
||||
className="absolute inset-0 w-full h-full object-cover"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex flex-col gap-0.5 px-2 py-1.5 text-left">
|
||||
<span className="line-clamp-2">{item.title}</span>
|
||||
<RelativeDate date={item.date} />
|
||||
</div>
|
||||
</FeedLink>
|
||||
);
|
||||
}
|
||||
|
||||
export default function Component({ service }) {
|
||||
const { t } = useTranslation();
|
||||
const { settings } = useContext(SettingsContext);
|
||||
const { widget } = service;
|
||||
|
||||
const { data, error } = useWidgetAPI(widget, undefined, undefined, { refreshInterval: 10 * 60 * 1000 });
|
||||
|
||||
if (error) {
|
||||
return <Container service={service} error={error} />;
|
||||
}
|
||||
|
||||
const target = service.target ?? settings?.target ?? "_blank";
|
||||
const isGrid = widget.layout === "grid";
|
||||
const Item = isGrid ? GridItem : ListItem;
|
||||
|
||||
let content;
|
||||
if (!data) {
|
||||
content = [0, 1, 2].map((i) => (
|
||||
<div key={i} className={classNames(rowClassName, "animate-pulse", isGrid ? "aspect-video" : "h-5")} />
|
||||
));
|
||||
} else if (!data.items?.length) {
|
||||
content = <div className={classNames(rowClassName, "h-5 px-2 flex items-center")}>{t("feed.noItems")}</div>;
|
||||
} else {
|
||||
content = data.items.map((item, i) => <Item key={`${item.link ?? item.title}-${i}`} item={item} target={target} />);
|
||||
}
|
||||
|
||||
return (
|
||||
<Container service={service}>
|
||||
<div
|
||||
className={classNames(
|
||||
"w-full p-1",
|
||||
isGrid ? "grid grid-cols-[repeat(auto-fill,minmax(8rem,1fr))] gap-2" : "flex flex-col gap-1",
|
||||
)}
|
||||
>
|
||||
{content}
|
||||
</div>
|
||||
</Container>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { screen } from "@testing-library/react";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { renderWithProviders } from "test-utils/render-with-providers";
|
||||
|
||||
const { useWidgetAPI } = vi.hoisted(() => ({ useWidgetAPI: vi.fn() }));
|
||||
vi.mock("utils/proxy/use-widget-api", () => ({ default: useWidgetAPI }));
|
||||
|
||||
import Component from "./component";
|
||||
|
||||
const items = [
|
||||
{
|
||||
title: "With image",
|
||||
link: "https://example.com/1",
|
||||
date: "2020-01-01T00:00:00Z",
|
||||
image: "https://example.com/1.jpg",
|
||||
},
|
||||
{ title: "No link", link: null, date: null },
|
||||
];
|
||||
|
||||
function render(widget = {}, settings = {}) {
|
||||
return renderWithProviders(<Component service={{ widget: { type: "feed", ...widget } }} />, {
|
||||
settings: { hideErrors: false, ...settings },
|
||||
});
|
||||
}
|
||||
|
||||
describe("widgets/feed/component", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("renders placeholders while loading", () => {
|
||||
useWidgetAPI.mockReturnValue({ data: undefined, error: undefined });
|
||||
const { container } = render();
|
||||
expect(container.querySelectorAll(".animate-pulse")).toHaveLength(3);
|
||||
});
|
||||
|
||||
it("renders an error", () => {
|
||||
useWidgetAPI.mockReturnValue({ data: undefined, error: { message: "Invalid feed" } });
|
||||
render();
|
||||
expect(screen.getAllByText(/Invalid feed/).length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it("renders an empty feed", () => {
|
||||
useWidgetAPI.mockReturnValue({ data: { items: [] }, error: undefined });
|
||||
render();
|
||||
expect(screen.getByText("feed.noItems")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("renders list items with links and images", () => {
|
||||
useWidgetAPI.mockReturnValue({ data: { items }, error: undefined });
|
||||
const { container } = render({}, { target: "_self" });
|
||||
|
||||
const link = screen.getByText("With image").closest("a");
|
||||
expect(link).toHaveAttribute("href", "https://example.com/1");
|
||||
expect(link).toHaveAttribute("target", "_self");
|
||||
expect(link.querySelector("img")).toHaveAttribute("src", "https://example.com/1.jpg");
|
||||
expect(screen.getByText("No link").closest("a")).toBeNull();
|
||||
expect(container.querySelectorAll("img")).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("renders the grid layout with image placeholders", () => {
|
||||
useWidgetAPI.mockReturnValue({ data: { items }, error: undefined });
|
||||
const { container } = render({ layout: "grid" });
|
||||
|
||||
expect(container.querySelector(".grid")).not.toBeNull();
|
||||
expect(container.querySelectorAll(".aspect-video")).toHaveLength(2);
|
||||
expect(container.querySelectorAll("img")).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("hides images that fail to load", () => {
|
||||
useWidgetAPI.mockReturnValue({ data: { items }, error: undefined });
|
||||
const { container } = render();
|
||||
const img = container.querySelector("img");
|
||||
img.dispatchEvent(new Event("error"));
|
||||
expect(img.style.visibility).toBe("hidden");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,61 @@
|
||||
import cache from "memory-cache";
|
||||
|
||||
import { parseFeed } from "./utils";
|
||||
|
||||
import getServiceWidget from "utils/config/service-helpers";
|
||||
import createLogger from "utils/logger";
|
||||
import { sanitizeErrorURL } from "utils/proxy/api-helpers";
|
||||
import { httpProxy } from "utils/proxy/http";
|
||||
|
||||
const logger = createLogger("feedProxyHandler");
|
||||
const CACHE_MS = 10 * 60 * 1000;
|
||||
|
||||
export default async function feedProxyHandler(req, res) {
|
||||
const { group, service, index } = req.query;
|
||||
const widget = await getServiceWidget(group, service, index);
|
||||
|
||||
if (!widget?.url) {
|
||||
return res.status(400).json({ error: "Missing feed URL" });
|
||||
}
|
||||
|
||||
let url;
|
||||
try {
|
||||
url = new URL(widget.url);
|
||||
} catch {
|
||||
return res.status(400).json({ error: "Invalid feed URL" });
|
||||
}
|
||||
|
||||
const cacheKey = `feed:${url.href}`;
|
||||
let items = cache.get(cacheKey);
|
||||
|
||||
if (!items) {
|
||||
const [status, , data] = await httpProxy(url, {
|
||||
headers: {
|
||||
"User-Agent": `gethomepage/${process.env.NEXT_PUBLIC_VERSION || "dev"}`,
|
||||
Accept: "application/rss+xml, application/atom+xml, application/xml;q=0.9, text/xml;q=0.9, */*;q=0.8",
|
||||
},
|
||||
});
|
||||
|
||||
if (status !== 200) {
|
||||
logger.debug("HTTP %d retrieving feed %s//%s%s", status, url.protocol, url.host, url.pathname);
|
||||
return res.status(status).json({ error: { message: "HTTP Error", url: sanitizeErrorURL(url) } });
|
||||
}
|
||||
|
||||
try {
|
||||
items = parseFeed(Buffer.from(data).toString(), url.href);
|
||||
} catch (e) {
|
||||
logger.debug("Error parsing feed %s//%s%s: %s", url.protocol, url.host, url.pathname, e.message);
|
||||
return res.status(500).json({ error: { message: "Invalid feed", url: sanitizeErrorURL(url) } });
|
||||
}
|
||||
|
||||
// only successful fetches are cached
|
||||
cache.put(cacheKey, items, CACHE_MS);
|
||||
}
|
||||
|
||||
const maxItems = parseInt(widget.maxItems, 10) || 5;
|
||||
const showImages = widget.images !== false && widget.images !== "false";
|
||||
|
||||
return res.status(200).json({
|
||||
items: items.slice(0, maxItems).map(({ image, ...item }) => (showImages && image ? { ...item, image } : item)),
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
import cache from "memory-cache";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import createMockRes from "test-utils/create-mock-res";
|
||||
|
||||
const { httpProxy, getServiceWidget, logger } = vi.hoisted(() => ({
|
||||
httpProxy: vi.fn(),
|
||||
getServiceWidget: vi.fn(),
|
||||
logger: {
|
||||
debug: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("utils/logger", () => ({
|
||||
default: () => logger,
|
||||
}));
|
||||
|
||||
vi.mock("utils/config/service-helpers", () => ({
|
||||
default: getServiceWidget,
|
||||
}));
|
||||
|
||||
vi.mock("utils/proxy/http", () => ({
|
||||
httpProxy,
|
||||
}));
|
||||
|
||||
import feedProxyHandler from "./proxy";
|
||||
|
||||
const items = Array.from(
|
||||
{ length: 7 },
|
||||
(_, i) => `<item><title>Item ${i}</title><link>https://example.com/${i}</link>
|
||||
<media:thumbnail url="https://example.com/${i}.jpg" /></item>`,
|
||||
).join("");
|
||||
const feed = `<rss xmlns:media="http://search.yahoo.com/mrss/"><channel>${items}</channel></rss>`;
|
||||
|
||||
const req = { query: { group: "g", service: "svc", index: "0" } };
|
||||
|
||||
describe("widgets/feed/proxy", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
cache.clear();
|
||||
});
|
||||
|
||||
it("returns 400 when the url is missing or invalid", async () => {
|
||||
getServiceWidget.mockResolvedValueOnce({ type: "feed" });
|
||||
let res = createMockRes();
|
||||
await feedProxyHandler(req, res);
|
||||
expect(res.statusCode).toBe(400);
|
||||
expect(res.body).toEqual({ error: "Missing feed URL" });
|
||||
|
||||
getServiceWidget.mockResolvedValueOnce({ type: "feed", url: "nope" });
|
||||
res = createMockRes();
|
||||
await feedProxyHandler(req, res);
|
||||
expect(res.statusCode).toBe(400);
|
||||
expect(res.body).toEqual({ error: "Invalid feed URL" });
|
||||
expect(httpProxy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("returns the first 5 items by default", async () => {
|
||||
getServiceWidget.mockResolvedValue({ type: "feed", url: "https://example.com/feed.xml" });
|
||||
httpProxy.mockResolvedValueOnce([200, "application/rss+xml", Buffer.from(feed)]);
|
||||
|
||||
const res = createMockRes();
|
||||
await feedProxyHandler(req, res);
|
||||
|
||||
expect(httpProxy.mock.calls[0][0].href).toBe("https://example.com/feed.xml");
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.body.items).toHaveLength(5);
|
||||
expect(res.body.items[0]).toEqual({
|
||||
title: "Item 0",
|
||||
link: "https://example.com/0",
|
||||
date: null,
|
||||
image: "https://example.com/0.jpg",
|
||||
});
|
||||
});
|
||||
|
||||
it("respects maxItems and drops images when disabled", async () => {
|
||||
getServiceWidget.mockResolvedValue({
|
||||
type: "feed",
|
||||
url: "https://example.com/feed.xml",
|
||||
maxItems: "2",
|
||||
images: false,
|
||||
});
|
||||
httpProxy.mockResolvedValueOnce([200, "application/rss+xml", Buffer.from(feed)]);
|
||||
|
||||
const res = createMockRes();
|
||||
await feedProxyHandler(req, res);
|
||||
|
||||
expect(res.body.items).toEqual([
|
||||
{ title: "Item 0", link: "https://example.com/0", date: null },
|
||||
{ title: "Item 1", link: "https://example.com/1", date: null },
|
||||
]);
|
||||
});
|
||||
|
||||
it("passes through http errors without leaking the url", async () => {
|
||||
getServiceWidget.mockResolvedValue({ type: "feed", url: "https://example.com/feed.xml?token=secret" });
|
||||
httpProxy.mockResolvedValueOnce([404, "text/html", Buffer.from("Not found")]);
|
||||
|
||||
const res = createMockRes();
|
||||
await feedProxyHandler(req, res);
|
||||
|
||||
expect(res.statusCode).toBe(404);
|
||||
expect(res.body).toEqual({ error: { message: "HTTP Error", url: "example.com (see logs for details)" } });
|
||||
});
|
||||
|
||||
it("returns 500 for unparseable feeds", async () => {
|
||||
getServiceWidget.mockResolvedValue({ type: "feed", url: "https://example.com/feed.xml" });
|
||||
httpProxy.mockResolvedValueOnce([200, "text/html", Buffer.from("<html></html>")]);
|
||||
|
||||
const res = createMockRes();
|
||||
await feedProxyHandler(req, res);
|
||||
|
||||
expect(res.statusCode).toBe(500);
|
||||
expect(res.body).toEqual({ error: { message: "Invalid feed", url: "example.com (see logs for details)" } });
|
||||
});
|
||||
|
||||
it("shares one cached fetch across widgets with different options", async () => {
|
||||
getServiceWidget
|
||||
.mockResolvedValueOnce({ type: "feed", url: "https://example.com/feed.xml", maxItems: 1 })
|
||||
.mockResolvedValueOnce({ type: "feed", url: "https://example.com/feed.xml", images: false });
|
||||
httpProxy.mockResolvedValue([200, "application/rss+xml", Buffer.from(feed)]);
|
||||
|
||||
const first = createMockRes();
|
||||
await feedProxyHandler(req, first);
|
||||
const second = createMockRes();
|
||||
await feedProxyHandler(req, second);
|
||||
|
||||
expect(httpProxy).toHaveBeenCalledTimes(1);
|
||||
expect(first.body.items).toHaveLength(1);
|
||||
expect(second.body.items).toHaveLength(5);
|
||||
expect(second.body.items[0].image).toBeUndefined();
|
||||
});
|
||||
|
||||
it("does not cache failures", async () => {
|
||||
getServiceWidget.mockResolvedValue({ type: "feed", url: "https://example.com/feed.xml" });
|
||||
httpProxy
|
||||
.mockResolvedValueOnce([404, "text/html", Buffer.from("Not found")])
|
||||
.mockResolvedValueOnce([200, "application/rss+xml", Buffer.from(feed)]);
|
||||
|
||||
const failed = createMockRes();
|
||||
await feedProxyHandler(req, failed);
|
||||
const recovered = createMockRes();
|
||||
await feedProxyHandler(req, recovered);
|
||||
|
||||
expect(failed.statusCode).toBe(404);
|
||||
expect(recovered.statusCode).toBe(200);
|
||||
expect(httpProxy).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,104 @@
|
||||
import sax from "sax";
|
||||
import { xml2js } from "xml-js";
|
||||
|
||||
const asArray = (value) => (value === undefined || value === null ? [] : [].concat(value));
|
||||
|
||||
function getText(node) {
|
||||
const first = asArray(node)[0];
|
||||
if (first === undefined) return "";
|
||||
if (typeof first !== "object") return String(first);
|
||||
return asArray(first._cdata ?? first._text).join("");
|
||||
}
|
||||
|
||||
export function httpUrl(value, baseUrl) {
|
||||
if (!value) return null;
|
||||
try {
|
||||
const url = new URL(value.trim(), baseUrl);
|
||||
return ["http:", "https:"].includes(url.protocol) ? url.href : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function parseDate(value) {
|
||||
const time = Date.parse(value);
|
||||
return Number.isNaN(time) ? null : new Date(time).toISOString();
|
||||
}
|
||||
|
||||
const attrs = (node) => node?._attributes ?? {};
|
||||
const isImage = (node) => attrs(node).medium === "image" || attrs(node).type?.startsWith("image/");
|
||||
|
||||
function findImage(item) {
|
||||
const groups = [item, ...asArray(item["media:group"])];
|
||||
const candidates = [
|
||||
...groups.flatMap((group) => asArray(group["media:thumbnail"])),
|
||||
...groups.flatMap((group) => asArray(group["media:content"])).filter(isImage),
|
||||
...asArray(item.enclosure).filter(isImage),
|
||||
...asArray(item.link).filter((link) => attrs(link).rel === "enclosure" && isImage(link)),
|
||||
];
|
||||
const image = candidates.find((node) => attrs(node).url || attrs(node).href);
|
||||
return image ? attrs(image).url || attrs(image).href : null;
|
||||
}
|
||||
|
||||
const isPixel = ({ width, height }) => ["0", "1"].includes(width) || ["0", "1"].includes(height);
|
||||
|
||||
// first usable <img> in item html using sax tokenizer
|
||||
function findHtmlImage(htmls, baseUrl) {
|
||||
for (const html of htmls) {
|
||||
if (!html) continue;
|
||||
let image = null;
|
||||
const parser = sax.parser(false, { lowercase: true });
|
||||
parser.onopentag = ({ name, attributes }) => {
|
||||
if (!image && name === "img" && !isPixel(attributes)) image = httpUrl(attributes.src, baseUrl);
|
||||
};
|
||||
parser.onerror = () => {
|
||||
parser.error = null;
|
||||
parser.resume();
|
||||
};
|
||||
parser.write(html).close();
|
||||
if (image) return image;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function parseRssItem(item) {
|
||||
const guid = asArray(item.guid)[0];
|
||||
const guidLink = attrs(guid).isPermaLink !== "false" ? getText(guid) : null;
|
||||
return {
|
||||
title: getText(item.title),
|
||||
link: getText(item.link) || guidLink,
|
||||
date: getText(item.pubDate) || getText(item["dc:date"]),
|
||||
image: findImage(item),
|
||||
html: [getText(item["content:encoded"]), getText(item.description)],
|
||||
};
|
||||
}
|
||||
|
||||
function parseAtomEntry(entry) {
|
||||
const links = asArray(entry.link);
|
||||
const link = links.find((l) => (attrs(l).rel ?? "alternate") === "alternate") ?? links[0];
|
||||
return {
|
||||
title: getText(entry.title),
|
||||
link: attrs(link).href,
|
||||
date: getText(entry.published) || getText(entry.updated),
|
||||
image: findImage(entry),
|
||||
html: [getText(entry.content), getText(entry.summary)],
|
||||
};
|
||||
}
|
||||
|
||||
export function parseFeed(xml, baseUrl) {
|
||||
const doc = xml2js(xml, { compact: true });
|
||||
|
||||
let items;
|
||||
if (doc.rss) items = asArray(doc.rss.channel?.item).map(parseRssItem);
|
||||
else if (doc.feed) items = asArray(doc.feed.entry).map(parseAtomEntry);
|
||||
else throw new Error("Unsupported feed format");
|
||||
|
||||
return items
|
||||
.map((item) => ({
|
||||
title: item.title.trim(),
|
||||
link: httpUrl(item.link, baseUrl),
|
||||
date: parseDate(item.date),
|
||||
image: httpUrl(item.image, baseUrl) ?? findHtmlImage(item.html, baseUrl),
|
||||
}))
|
||||
.filter((item) => item.title);
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { httpUrl, parseFeed } from "./utils";
|
||||
|
||||
const rss = `<?xml version="1.0"?>
|
||||
<rss version="2.0" xmlns:media="http://search.yahoo.com/mrss/" xmlns:dc="http://purl.org/dc/elements/1.1/">
|
||||
<channel>
|
||||
<title>Example</title>
|
||||
<item>
|
||||
<title><![CDATA[Tom & Jerry]]></title>
|
||||
<link>https://example.com/one</link>
|
||||
<pubDate>Tue, 22 Sep 2026 10:00:00 GMT</pubDate>
|
||||
<media:thumbnail url="https://img.example.com/one.jpg" />
|
||||
</item>
|
||||
<item>
|
||||
<title>Enclosure image</title>
|
||||
<guid>https://example.com/two</guid>
|
||||
<dc:date>2026-09-21T10:00:00Z</dc:date>
|
||||
<enclosure url="/two.png" type="image/png" length="1" />
|
||||
</item>
|
||||
<item>
|
||||
<title>Audio only</title>
|
||||
<link>javascript:alert(1)</link>
|
||||
<guid isPermaLink="false">abc-123</guid>
|
||||
<enclosure url="https://example.com/three.mp3" type="audio/mpeg" length="1" />
|
||||
</item>
|
||||
<item>
|
||||
<description>No title, skipped</description>
|
||||
</item>
|
||||
</channel>
|
||||
</rss>`;
|
||||
|
||||
const atom = `<?xml version="1.0" encoding="utf-8"?>
|
||||
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/">
|
||||
<title>Example</title>
|
||||
<entry>
|
||||
<title> Fish & chips
|
||||
</title>
|
||||
<link rel="enclosure" type="image/jpeg" href="https://example.com/one.jpg" />
|
||||
<link rel="alternate" href="https://example.com/one" />
|
||||
<updated>2026-09-22T12:00:00Z</updated>
|
||||
</entry>
|
||||
<entry>
|
||||
<title>YouTube style</title>
|
||||
<link href="https://example.com/two" />
|
||||
<published>2026-09-20T12:00:00Z</published>
|
||||
<updated>not a date</updated>
|
||||
<media:group>
|
||||
<media:content url="https://example.com/two.mp4" type="video/mp4" />
|
||||
<media:thumbnail url="https://example.com/two.jpg" />
|
||||
</media:group>
|
||||
</entry>
|
||||
</feed>`;
|
||||
|
||||
describe("widgets/feed/utils", () => {
|
||||
it("parses rss 2.0 items", () => {
|
||||
expect(parseFeed(rss, "https://example.com/feed.xml")).toEqual([
|
||||
{
|
||||
title: "Tom & Jerry",
|
||||
link: "https://example.com/one",
|
||||
date: "2026-09-22T10:00:00.000Z",
|
||||
image: "https://img.example.com/one.jpg",
|
||||
},
|
||||
{
|
||||
title: "Enclosure image",
|
||||
link: "https://example.com/two",
|
||||
date: "2026-09-21T10:00:00.000Z",
|
||||
image: "https://example.com/two.png",
|
||||
},
|
||||
{ title: "Audio only", link: null, date: null, image: null },
|
||||
]);
|
||||
});
|
||||
|
||||
it("parses atom entries", () => {
|
||||
expect(parseFeed(atom, "https://example.com/atom.xml")).toEqual([
|
||||
{
|
||||
title: "Fish & chips",
|
||||
link: "https://example.com/one",
|
||||
date: "2026-09-22T12:00:00.000Z",
|
||||
image: "https://example.com/one.jpg",
|
||||
},
|
||||
{
|
||||
title: "YouTube style",
|
||||
link: "https://example.com/two",
|
||||
date: "2026-09-20T12:00:00.000Z",
|
||||
image: "https://example.com/two.jpg",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("falls back to the first usable image in item html", () => {
|
||||
const xml = `<rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:media="http://search.yahoo.com/mrss/"><channel>
|
||||
<item>
|
||||
<title>Content image</title>
|
||||
<content:encoded><![CDATA[<p>Hi <img src="https://t.example.com/p.gif" width="1" height="1">
|
||||
<img src="data:image/gif;base64,R0"><IMG SRC="/big.jpg?w=925&h=925"><img src="/second.jpg">]]></content:encoded>
|
||||
</item>
|
||||
<item>
|
||||
<title>Description image</title>
|
||||
<description><img src="https://example.com/desc.png"> unclosed <b></description>
|
||||
</item>
|
||||
<item>
|
||||
<title>Media wins</title>
|
||||
<media:thumbnail url="https://example.com/thumb.jpg" />
|
||||
<description><![CDATA[<img src="https://example.com/html.jpg">]]></description>
|
||||
</item>
|
||||
<item>
|
||||
<title>No usable image</title>
|
||||
<description><![CDATA[<img src="javascript:alert(1)"><img>]]></description>
|
||||
</item>
|
||||
</channel></rss>`;
|
||||
|
||||
expect(parseFeed(xml, "https://example.com/feed").map((item) => item.image)).toEqual([
|
||||
"https://example.com/big.jpg?w=925&h=925",
|
||||
"https://example.com/desc.png",
|
||||
"https://example.com/thumb.jpg",
|
||||
null,
|
||||
]);
|
||||
});
|
||||
|
||||
it("finds images in atom html content and summary", () => {
|
||||
const xml = `<feed xmlns="http://www.w3.org/2005/Atom">
|
||||
<entry><title>Content</title><content type="html"><img src="https://example.com/c.jpg"></content></entry>
|
||||
<entry><title>Summary</title><summary type="html"><img src="https://example.com/s.jpg"></summary></entry>
|
||||
</feed>`;
|
||||
|
||||
expect(parseFeed(xml).map((item) => item.image)).toEqual([
|
||||
"https://example.com/c.jpg",
|
||||
"https://example.com/s.jpg",
|
||||
]);
|
||||
});
|
||||
|
||||
it("handles single-item and empty feeds", () => {
|
||||
const single = "<rss><channel><item><title>Only</title></item></channel></rss>";
|
||||
expect(parseFeed(single)).toEqual([{ title: "Only", link: null, date: null, image: null }]);
|
||||
expect(parseFeed("<feed></feed>")).toEqual([]);
|
||||
});
|
||||
|
||||
it("rejects unsupported documents", () => {
|
||||
expect(() => parseFeed("<html><body>nope</body></html>")).toThrow("Unsupported feed format");
|
||||
expect(() => parseFeed("not xml <")).toThrow();
|
||||
});
|
||||
|
||||
it.each([
|
||||
["https://a.com/x", undefined, "https://a.com/x"],
|
||||
["/x", "https://a.com/feed", "https://a.com/x"],
|
||||
["data:image/png;base64,AAAA", undefined, null],
|
||||
["not a url", undefined, null],
|
||||
["", undefined, null],
|
||||
])("httpUrl(%j, %j) is %j", (value, base, expected) => {
|
||||
expect(httpUrl(value, base)).toBe(expected);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,8 @@
|
||||
import feedProxyHandler from "./proxy";
|
||||
|
||||
const widget = {
|
||||
api: "{url}",
|
||||
proxyHandler: feedProxyHandler,
|
||||
};
|
||||
|
||||
export default widget;
|
||||
@@ -0,0 +1,12 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { expectWidgetConfigShape } from "test-utils/widget-config";
|
||||
|
||||
import widget from "./widget";
|
||||
|
||||
describe("feed widget config", () => {
|
||||
it("exports a valid widget config", () => {
|
||||
expectWidgetConfigShape(widget);
|
||||
expect(widget.api).toBe("{url}");
|
||||
});
|
||||
});
|
||||
@@ -10,7 +10,8 @@ const widget = {
|
||||
},
|
||||
"nodes/localhost/tasks": {
|
||||
endpoint: "nodes/localhost/tasks",
|
||||
params: ["errors", "limit", "since"],
|
||||
params: ["errors", "limit"],
|
||||
optionalParams: ["since"],
|
||||
},
|
||||
"nodes/localhost/status": {
|
||||
endpoint: "nodes/localhost/status",
|
||||
|
||||
@@ -9,7 +9,8 @@ describe("proxmoxbackupserver widget config", () => {
|
||||
expectWidgetConfigShape(widget);
|
||||
});
|
||||
|
||||
it("requires failed task query params for the tasks endpoint", () => {
|
||||
expect(widget.mappings["nodes/localhost/tasks"].params).toEqual(["errors", "limit", "since"]);
|
||||
it("requires failed task query params for the tasks endpoint, with since optional", () => {
|
||||
expect(widget.mappings["nodes/localhost/tasks"].params).toEqual(["errors", "limit"]);
|
||||
expect(widget.mappings["nodes/localhost/tasks"].optionalParams).toEqual(["since"]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -31,6 +31,7 @@ import duplicati from "./duplicati/widget";
|
||||
import emby from "./emby/widget";
|
||||
import esphome from "./esphome/widget";
|
||||
import evcc from "./evcc/widget";
|
||||
import feed from "./feed/widget";
|
||||
import filebrowser from "./filebrowser/widget";
|
||||
import fileflows from "./fileflows/widget";
|
||||
import firefly from "./firefly/widget";
|
||||
@@ -191,6 +192,7 @@ const widgets = {
|
||||
emby,
|
||||
esphome,
|
||||
evcc,
|
||||
feed,
|
||||
filebrowser,
|
||||
fileflows,
|
||||
firefly,
|
||||
|
||||
Reference in New Issue
Block a user