mirror of
https://github.com/gethomepage/homepage.git
synced 2026-10-01 08:21:18 -07:00
Feature: Bookorbit service widget (#7202)
Docker CI / Docker Build & Push (push) Waiting to run
Lint / Linting Checks (push) Waiting to run
Release Drafter / Update Release Draft (push) Waiting to run
Release Drafter / Auto Label PR (push) Waiting to run
Tests / vitest (1) (push) Waiting to run
Tests / vitest (2) (push) Waiting to run
Tests / vitest (3) (push) Waiting to run
Tests / vitest (4) (push) Waiting to run
Docker CI / Docker Build & Push (push) Waiting to run
Lint / Linting Checks (push) Waiting to run
Release Drafter / Update Release Draft (push) Waiting to run
Release Drafter / Auto Label PR (push) Waiting to run
Tests / vitest (1) (push) Waiting to run
Tests / vitest (2) (push) Waiting to run
Tests / vitest (3) (push) Waiting to run
Tests / vitest (4) (push) Waiting to run
This commit is contained in:
@@ -0,0 +1,21 @@
|
||||
---
|
||||
title: BookOrbit
|
||||
description: BookOrbit Widget Configuration
|
||||
---
|
||||
|
||||
Learn more about [BookOrbit](https://github.com/bookorbit/bookorbit).
|
||||
|
||||
```yaml
|
||||
widget:
|
||||
type: bookorbit
|
||||
url: http://bookorbit.host.or.ip:3000
|
||||
username: username
|
||||
password: password
|
||||
fields: ["books", "authors", "reading", "finished"] # optional
|
||||
```
|
||||
|
||||
## Fields
|
||||
|
||||
Allowed fields: `["books", "authors", "series", "storage", "reading", "finished"]` (maximum of 4).
|
||||
|
||||
Default fields: `["books", "authors", "reading", "finished"]`.
|
||||
@@ -19,6 +19,7 @@ You can also find a list of all available service widgets in the sidebar navigat
|
||||
- [Backrest](backrest.md)
|
||||
- [Bazarr](bazarr.md)
|
||||
- [Booklore](booklore.md)
|
||||
- [BookOrbit](bookorbit.md)
|
||||
- [Beszel](beszel.md)
|
||||
- [Caddy](caddy.md)
|
||||
- [Calendar](calendar.md)
|
||||
|
||||
@@ -44,6 +44,7 @@ nav:
|
||||
- widgets/services/backrest.md
|
||||
- widgets/services/bazarr.md
|
||||
- widgets/services/booklore.md
|
||||
- widgets/services/bookorbit.md
|
||||
- widgets/services/beszel.md
|
||||
- widgets/services/caddy.md
|
||||
- widgets/services/calendar.md
|
||||
|
||||
@@ -869,6 +869,14 @@
|
||||
"reading": "Reading",
|
||||
"finished": "Finished"
|
||||
},
|
||||
"bookorbit": {
|
||||
"books": "Books",
|
||||
"authors": "Authors",
|
||||
"series": "Series",
|
||||
"storage": "Storage",
|
||||
"reading": "Reading",
|
||||
"finished": "Finished"
|
||||
},
|
||||
"jdownloader": {
|
||||
"downloadCount": "Queue",
|
||||
"downloadBytesRemaining": "Remaining",
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import { useTranslation } from "next-i18next/pages";
|
||||
|
||||
import Block from "components/services/widget/block";
|
||||
import Container from "components/services/widget/container";
|
||||
import useWidgetAPI from "utils/proxy/use-widget-api";
|
||||
import withWidgetFields from "utils/widget-fields";
|
||||
|
||||
const DEFAULT_FIELDS = ["books", "authors", "reading", "finished"];
|
||||
|
||||
export default function Component({ service: configuredService }) {
|
||||
const { t } = useTranslation();
|
||||
const service = withWidgetFields(configuredService, DEFAULT_FIELDS);
|
||||
const { widget } = service;
|
||||
|
||||
const { data, error } = useWidgetAPI(widget);
|
||||
|
||||
if (error) {
|
||||
return <Container service={service} error={error} />;
|
||||
}
|
||||
|
||||
if (!data) {
|
||||
return (
|
||||
<Container service={service}>
|
||||
<Block label="bookorbit.books" />
|
||||
<Block label="bookorbit.authors" />
|
||||
<Block label="bookorbit.series" />
|
||||
<Block label="bookorbit.storage" />
|
||||
<Block label="bookorbit.reading" />
|
||||
<Block label="bookorbit.finished" />
|
||||
</Container>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Container service={service}>
|
||||
<Block label="bookorbit.books" value={t("common.number", { value: data.books })} />
|
||||
<Block label="bookorbit.authors" value={t("common.number", { value: data.authors })} />
|
||||
<Block label="bookorbit.series" value={t("common.number", { value: data.series })} />
|
||||
<Block label="bookorbit.storage" value={t("common.bbytes", { value: data.storage, maximumFractionDigits: 1 })} />
|
||||
<Block label="bookorbit.reading" value={t("common.number", { value: data.reading })} />
|
||||
<Block label="bookorbit.finished" value={t("common.number", { value: data.finished })} />
|
||||
</Container>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
// @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";
|
||||
import { expectBlockValue } from "test-utils/widget-assertions";
|
||||
|
||||
const { useWidgetAPI } = vi.hoisted(() => ({ useWidgetAPI: vi.fn() }));
|
||||
vi.mock("utils/proxy/use-widget-api", () => ({ default: useWidgetAPI }));
|
||||
|
||||
import Component from "./component";
|
||||
|
||||
const data = { books: 1200, authors: 300, series: 45, storage: 1024, reading: 2, finished: 80 };
|
||||
|
||||
describe("widgets/bookorbit/component", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("renders default placeholders while loading", () => {
|
||||
useWidgetAPI.mockReturnValue({ data: undefined, error: undefined });
|
||||
|
||||
const { container } = renderWithProviders(<Component service={{ widget: { type: "bookorbit" } }} />, {
|
||||
settings: { hideErrors: false },
|
||||
});
|
||||
|
||||
expect(container.querySelectorAll(".service-block")).toHaveLength(4);
|
||||
expect(screen.getByText("bookorbit.books")).toBeInTheDocument();
|
||||
expect(screen.getByText("bookorbit.authors")).toBeInTheDocument();
|
||||
expect(screen.getByText("bookorbit.reading")).toBeInTheDocument();
|
||||
expect(screen.getByText("bookorbit.finished")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("renders error UI when the endpoint errors", () => {
|
||||
useWidgetAPI.mockReturnValue({ data: undefined, error: { message: "nope" } });
|
||||
|
||||
renderWithProviders(<Component service={{ widget: { type: "bookorbit" } }} />, { settings: { hideErrors: false } });
|
||||
|
||||
expect(screen.getAllByText(/widget\.api_error/i).length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it("renders the default fields", () => {
|
||||
useWidgetAPI.mockReturnValue({ data, error: undefined });
|
||||
|
||||
const { container } = renderWithProviders(<Component service={{ widget: { type: "bookorbit" } }} />, {
|
||||
settings: { hideErrors: false },
|
||||
});
|
||||
|
||||
expect(container.querySelectorAll(".service-block")).toHaveLength(4);
|
||||
expectBlockValue(container, "bookorbit.books", 1200);
|
||||
expectBlockValue(container, "bookorbit.authors", 300);
|
||||
expectBlockValue(container, "bookorbit.reading", 2);
|
||||
expectBlockValue(container, "bookorbit.finished", 80);
|
||||
});
|
||||
|
||||
it("renders configured fields", () => {
|
||||
useWidgetAPI.mockReturnValue({ data, error: undefined });
|
||||
|
||||
const service = { widget: { type: "bookorbit", fields: ["series", "storage"] } };
|
||||
const { container } = renderWithProviders(<Component service={service} />, { settings: { hideErrors: false } });
|
||||
|
||||
expect(container.querySelectorAll(".service-block")).toHaveLength(2);
|
||||
expectBlockValue(container, "bookorbit.series", 45);
|
||||
expectBlockValue(container, "bookorbit.storage", 1024);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,137 @@
|
||||
import cache from "memory-cache";
|
||||
|
||||
import getServiceWidget from "utils/config/service-helpers";
|
||||
import createLogger from "utils/logger";
|
||||
import { formatApiCall } from "utils/proxy/api-helpers";
|
||||
import { httpProxy } from "utils/proxy/http";
|
||||
import widgets from "widgets/widgets";
|
||||
|
||||
const proxyName = "bookorbitProxyHandler";
|
||||
const accessTokenCacheKey = `${proxyName}__accessToken`;
|
||||
const refreshTokenCacheKey = `${proxyName}__refreshToken`;
|
||||
const logger = createLogger(proxyName);
|
||||
|
||||
async function requestTokens(widget, service, endpoint, body) {
|
||||
const url = new URL(formatApiCall(widgets[widget.type].api, { ...widget, endpoint }));
|
||||
const [status, , data] = await httpProxy(url, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json", accept: "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
|
||||
if (status !== 200) {
|
||||
logger.debug("BookOrbit %s failed for service '%s' with status %d", endpoint, service, status);
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const { accessToken, refreshToken } = JSON.parse(data.toString());
|
||||
if (!accessToken) return null;
|
||||
|
||||
// expired tokens are replaced when a request gets a 401
|
||||
cache.put(`${accessTokenCacheKey}.${service}`, accessToken);
|
||||
if (refreshToken) cache.put(`${refreshTokenCacheKey}.${service}`, refreshToken);
|
||||
return accessToken;
|
||||
} catch (e) {
|
||||
logger.error("Unable to parse BookOrbit %s response: %s", endpoint, e);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
async function loginOrRefresh(widget, service, forceNew = false) {
|
||||
if (!forceNew) {
|
||||
const cached = cache.get(`${accessTokenCacheKey}.${service}`);
|
||||
if (cached) return cached;
|
||||
}
|
||||
|
||||
const refreshToken = cache.get(`${refreshTokenCacheKey}.${service}`);
|
||||
if (refreshToken) {
|
||||
const accessToken = await requestTokens(widget, service, "auth/refresh", { refreshToken });
|
||||
if (accessToken) return accessToken;
|
||||
cache.del(`${refreshTokenCacheKey}.${service}`);
|
||||
}
|
||||
|
||||
// native clients get the refresh token in the body
|
||||
return requestTokens(widget, service, "auth/login", {
|
||||
username: widget.username,
|
||||
password: widget.password,
|
||||
clientKind: "native",
|
||||
deviceLabel: "Homepage",
|
||||
});
|
||||
}
|
||||
|
||||
async function apiCall(widget, endpoint, service) {
|
||||
const url = new URL(formatApiCall(widgets[widget.type].api, { ...widget, endpoint }));
|
||||
const request = async (accessToken) =>
|
||||
httpProxy(url, {
|
||||
method: "GET",
|
||||
headers: { accept: "application/json", Authorization: `Bearer ${accessToken}` },
|
||||
});
|
||||
|
||||
let accessToken = await loginOrRefresh(widget, service);
|
||||
if (!accessToken) return { status: 401, data: null };
|
||||
|
||||
let [status, , data] = await request(accessToken);
|
||||
|
||||
if (status === 401) {
|
||||
logger.debug("BookOrbit API rejected the request, attempting to obtain a new access token");
|
||||
cache.del(`${accessTokenCacheKey}.${service}`);
|
||||
accessToken = await loginOrRefresh(widget, service, true);
|
||||
if (!accessToken) return { status, data: null };
|
||||
[status, , data] = await request(accessToken);
|
||||
}
|
||||
|
||||
if (status !== 200) {
|
||||
logger.error("Error getting data from BookOrbit: %s status %d. Data: %s", url, status, data);
|
||||
return { status, data: null };
|
||||
}
|
||||
|
||||
try {
|
||||
return { status, data: JSON.parse(data.toString()) };
|
||||
} catch (e) {
|
||||
logger.error("Error parsing BookOrbit response: %s", e);
|
||||
}
|
||||
|
||||
return { status: 500, data: null };
|
||||
}
|
||||
|
||||
export default async function bookorbitProxyHandler(req, res) {
|
||||
const { group, service, index } = req.query;
|
||||
|
||||
if (!group || !service) {
|
||||
logger.debug("Invalid or missing service '%s' or group '%s'", service, group);
|
||||
return res.status(400).json({ error: "Invalid proxy service type" });
|
||||
}
|
||||
|
||||
const widget = await getServiceWidget(group, service, index);
|
||||
|
||||
if (!widget) {
|
||||
logger.debug("Invalid or missing widget for service '%s' in group '%s'", service, group);
|
||||
return res.status(400).json({ error: "Invalid proxy service type" });
|
||||
}
|
||||
|
||||
if (!widget.username || !widget.password) {
|
||||
logger.debug("Missing credentials for BookOrbit widget in service '%s'", service);
|
||||
return res.status(400).json({ error: "Missing BookOrbit credentials" });
|
||||
}
|
||||
|
||||
const library = await apiCall(widget, "statistics/summary", service);
|
||||
if (!library.data) {
|
||||
return res.status(library.status).json({ error: "Error fetching BookOrbit library statistics" });
|
||||
}
|
||||
|
||||
const reading = await apiCall(widget, "user-statistics/summary", service);
|
||||
if (!reading.data) {
|
||||
return res.status(reading.status).json({ error: "Error fetching BookOrbit reading statistics" });
|
||||
}
|
||||
|
||||
return res.status(200).json({
|
||||
books: library.data.totalBooks,
|
||||
authors: library.data.totalAuthors,
|
||||
series: library.data.totalSeries,
|
||||
storage: library.data.totalStorageBytes,
|
||||
reading: reading.data.inProgressBooks,
|
||||
finished: reading.data.completedBooks,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import createMockRes from "test-utils/create-mock-res";
|
||||
|
||||
const { httpProxy, getServiceWidget, cache, logger } = vi.hoisted(() => {
|
||||
const store = new Map();
|
||||
|
||||
return {
|
||||
httpProxy: vi.fn(),
|
||||
getServiceWidget: vi.fn(),
|
||||
cache: {
|
||||
get: vi.fn((k) => store.get(k)),
|
||||
put: vi.fn((k, v) => store.set(k, v)),
|
||||
del: vi.fn((k) => store.delete(k)),
|
||||
_reset: () => store.clear(),
|
||||
},
|
||||
logger: {
|
||||
debug: vi.fn(),
|
||||
error: vi.fn(),
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("utils/logger", () => ({ default: () => logger }));
|
||||
vi.mock("utils/config/service-helpers", () => ({ default: getServiceWidget }));
|
||||
vi.mock("utils/proxy/http", () => ({ httpProxy }));
|
||||
vi.mock("memory-cache", () => ({ default: cache, ...cache }));
|
||||
vi.mock("widgets/widgets", () => ({
|
||||
default: { bookorbit: { api: "{url}/api/v1/{endpoint}" } },
|
||||
}));
|
||||
|
||||
import bookorbitProxyHandler from "./proxy";
|
||||
|
||||
const widget = { type: "bookorbit", url: "http://bookorbit", username: "u", password: "p" };
|
||||
const req = { query: { group: "g", service: "svc", index: "0" } };
|
||||
|
||||
const json = (body, status = 200) => [status, "application/json", Buffer.from(JSON.stringify(body))];
|
||||
const tokens = (n) => ({ accessToken: `access${n}`, refreshToken: `refresh${n}` });
|
||||
const summary = { totalBooks: 10, totalAuthors: 4, totalSeries: 2, totalStorageBytes: 2048 };
|
||||
const userSummary = { inProgressBooks: 1, completedBooks: 3 };
|
||||
|
||||
describe("widgets/bookorbit/proxy", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
cache._reset();
|
||||
});
|
||||
|
||||
it("returns 400 when credentials are missing", async () => {
|
||||
getServiceWidget.mockResolvedValue({ type: "bookorbit", url: "http://bookorbit" });
|
||||
const res = createMockRes();
|
||||
|
||||
await bookorbitProxyHandler(req, res);
|
||||
|
||||
expect(res.statusCode).toBe(400);
|
||||
expect(res.body).toEqual({ error: "Missing BookOrbit credentials" });
|
||||
});
|
||||
|
||||
it("logs in as a native client and combines library and reading stats", async () => {
|
||||
getServiceWidget.mockResolvedValue(widget);
|
||||
httpProxy
|
||||
.mockResolvedValueOnce(json(tokens(1)))
|
||||
.mockResolvedValueOnce(json(summary))
|
||||
.mockResolvedValueOnce(json(userSummary));
|
||||
const res = createMockRes();
|
||||
|
||||
await bookorbitProxyHandler(req, res);
|
||||
|
||||
expect(httpProxy).toHaveBeenCalledTimes(3);
|
||||
expect(JSON.parse(httpProxy.mock.calls[0][1].body)).toEqual(
|
||||
expect.objectContaining({ username: "u", password: "p", clientKind: "native" }),
|
||||
);
|
||||
expect(httpProxy.mock.calls[1][0].toString()).toBe("http://bookorbit/api/v1/statistics/summary");
|
||||
expect(httpProxy.mock.calls[1][1].headers.Authorization).toBe("Bearer access1");
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.body).toEqual({ books: 10, authors: 4, series: 2, storage: 2048, reading: 1, finished: 3 });
|
||||
});
|
||||
|
||||
it("reuses the cached access token", async () => {
|
||||
getServiceWidget.mockResolvedValue(widget);
|
||||
httpProxy
|
||||
.mockResolvedValueOnce(json(tokens(1)))
|
||||
.mockResolvedValueOnce(json(summary))
|
||||
.mockResolvedValueOnce(json(userSummary))
|
||||
.mockResolvedValueOnce(json(summary))
|
||||
.mockResolvedValueOnce(json(userSummary));
|
||||
|
||||
await bookorbitProxyHandler(req, createMockRes());
|
||||
await bookorbitProxyHandler(req, createMockRes());
|
||||
|
||||
const loginCalls = httpProxy.mock.calls.filter(([url]) => url.toString().includes("auth/"));
|
||||
expect(loginCalls).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("uses the refresh token when the access token is rejected", async () => {
|
||||
getServiceWidget.mockResolvedValue(widget);
|
||||
httpProxy
|
||||
.mockResolvedValueOnce(json(tokens(1)))
|
||||
.mockResolvedValueOnce(json({}, 401))
|
||||
.mockResolvedValueOnce(json(tokens(2)))
|
||||
.mockResolvedValueOnce(json(summary))
|
||||
.mockResolvedValueOnce(json(userSummary));
|
||||
const res = createMockRes();
|
||||
|
||||
await bookorbitProxyHandler(req, res);
|
||||
|
||||
expect(httpProxy.mock.calls[2][0].toString()).toBe("http://bookorbit/api/v1/auth/refresh");
|
||||
expect(JSON.parse(httpProxy.mock.calls[2][1].body)).toEqual({ refreshToken: "refresh1" });
|
||||
expect(httpProxy.mock.calls[3][1].headers.Authorization).toBe("Bearer access2");
|
||||
expect(res.statusCode).toBe(200);
|
||||
});
|
||||
|
||||
it("falls back to logging in when the refresh token is rejected", async () => {
|
||||
getServiceWidget.mockResolvedValue(widget);
|
||||
httpProxy
|
||||
.mockResolvedValueOnce(json(tokens(1)))
|
||||
.mockResolvedValueOnce(json({}, 401))
|
||||
.mockResolvedValueOnce(json({}, 401))
|
||||
.mockResolvedValueOnce(json(tokens(3)))
|
||||
.mockResolvedValueOnce(json(summary))
|
||||
.mockResolvedValueOnce(json(userSummary));
|
||||
const res = createMockRes();
|
||||
|
||||
await bookorbitProxyHandler(req, res);
|
||||
|
||||
expect(httpProxy.mock.calls[3][0].toString()).toBe("http://bookorbit/api/v1/auth/login");
|
||||
expect(httpProxy.mock.calls[4][1].headers.Authorization).toBe("Bearer access3");
|
||||
expect(res.statusCode).toBe(200);
|
||||
});
|
||||
|
||||
it("returns an error when login fails", async () => {
|
||||
getServiceWidget.mockResolvedValue(widget);
|
||||
httpProxy.mockResolvedValueOnce(json({ message: "Invalid credentials" }, 401));
|
||||
const res = createMockRes();
|
||||
|
||||
await bookorbitProxyHandler(req, res);
|
||||
|
||||
expect(res.statusCode).toBe(401);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,8 @@
|
||||
import bookorbitProxyHandler from "./proxy";
|
||||
|
||||
const widget = {
|
||||
api: "{url}/api/v1/{endpoint}",
|
||||
proxyHandler: bookorbitProxyHandler,
|
||||
};
|
||||
|
||||
export default widget;
|
||||
@@ -0,0 +1,11 @@
|
||||
import { describe, it } from "vitest";
|
||||
|
||||
import { expectWidgetConfigShape } from "test-utils/widget-config";
|
||||
|
||||
import widget from "./widget";
|
||||
|
||||
describe("bookorbit widget config", () => {
|
||||
it("exports a valid widget config", () => {
|
||||
expectWidgetConfigShape(widget);
|
||||
});
|
||||
});
|
||||
@@ -14,6 +14,7 @@ const components = {
|
||||
bazarr: dynamic(() => import("./bazarr/component")),
|
||||
beszel: dynamic(() => import("./beszel/component")),
|
||||
booklore: dynamic(() => import("./booklore/component")),
|
||||
bookorbit: dynamic(() => import("./bookorbit/component")),
|
||||
caddy: dynamic(() => import("./caddy/component")),
|
||||
calendar: dynamic(() => import("./calendar/component")),
|
||||
calibreweb: dynamic(() => import("./calibreweb/component")),
|
||||
|
||||
@@ -11,6 +11,7 @@ import backrest from "./backrest/widget";
|
||||
import bazarr from "./bazarr/widget";
|
||||
import beszel from "./beszel/widget";
|
||||
import booklore from "./booklore/widget";
|
||||
import bookorbit from "./bookorbit/widget";
|
||||
import caddy from "./caddy/widget";
|
||||
import calendar from "./calendar/widget";
|
||||
import calibreweb from "./calibreweb/widget";
|
||||
@@ -173,6 +174,7 @@ const widgets = {
|
||||
backrest,
|
||||
bazarr,
|
||||
booklore,
|
||||
bookorbit,
|
||||
beszel,
|
||||
caddy,
|
||||
calibreweb,
|
||||
|
||||
Reference in New Issue
Block a user