diff --git a/.env.example b/.env.example
index 15fcd60..391990b 100644
--- a/.env.example
+++ b/.env.example
@@ -35,6 +35,11 @@
SPOOLMAN_HOST=0.0.0.0
SPOOLMAN_PORT=7912
+# Change base path
+# Set this if you want to host Spoolman at a sub-path
+# If you want the root to be e.g. myhost.com/spoolman
+# Then set this to /spoolman
+#SPOOLMAN_BASE_PATH=
# Enable Collect Prometheus metrics at database
# Default: FALSE
diff --git a/client/index.html b/client/index.html
index 14fb6df..54cf622 100644
--- a/client/index.html
+++ b/client/index.html
@@ -2,12 +2,12 @@
-
+
Spoolman
diff --git a/client/src/App.tsx b/client/src/App.tsx
index fbcddf3..85f5ad4 100644
--- a/client/src/App.tsx
+++ b/client/src/App.tsx
@@ -26,6 +26,8 @@ import loadable from "@loadable/component";
import SpoolmanNotificationProvider from "./components/notificationProvider";
import { SpoolmanLayout } from "./components/layout";
import liveProvider from "./components/liveProvider";
+import { getAPIURL, getBasePath } from "./utils/url";
+import { Favicon } from "./components/favicon";
interface ResourcePageProps {
resource: "spools" | "filaments" | "vendors";
@@ -84,7 +86,7 @@ function App() {
}
return (
-
+
+
diff --git a/client/src/components/favicon.tsx b/client/src/components/favicon.tsx
new file mode 100644
index 0000000..64d1a02
--- /dev/null
+++ b/client/src/components/favicon.tsx
@@ -0,0 +1,20 @@
+import { useEffect } from "react";
+
+/**
+ * Renders a favicon element in the head of the HTML document with the specified URL.
+ *
+ * @param {string} props.url - The URL of the favicon image.
+ * @return {JSX.Element} - An empty JSX element.
+ */
+export function Favicon(props: { url: string }) {
+ useEffect(() => {
+ let link = document.querySelector("link[rel~='icon']") as HTMLLinkElement;
+ if (!link) {
+ link = document.createElement("link") as HTMLLinkElement;
+ link.rel = "icon";
+ document.getElementsByTagName("head")[0].appendChild(link);
+ }
+ link.href = props.url;
+ }, [props.url]);
+ return <>>;
+}
diff --git a/client/src/components/layout.tsx b/client/src/components/layout.tsx
index 32177b9..36b7ada 100644
--- a/client/src/components/layout.tsx
+++ b/client/src/components/layout.tsx
@@ -5,6 +5,7 @@ import { Version } from "./version";
import { Button } from "antd";
import Logo from "../icon.svg?react";
import { useTranslate } from "@refinedev/core";
+import { getBasePath } from "../utils/url";
const SpoolmanFooter: React.FC = () => {
const t = useTranslate();
@@ -27,7 +28,7 @@ const SpoolmanFooter: React.FC = () => {
({
enabled: enabled,
queryKey: ["filaments"],
queryFn: async () => {
- const response = await fetch(apiEndpoint + "/filament");
+ const response = await fetch(getAPIURL() + "/filament");
if (!response.ok) {
throw new Error("Network response was not ok");
}
@@ -86,12 +86,11 @@ export function useSpoolmanFilamentFilter(enabled: boolean = false) {
}
export function useSpoolmanFilamentNames(enabled: boolean = false) {
- const apiEndpoint = import.meta.env.VITE_APIURL;
return useQuery({
enabled: enabled,
queryKey: ["filaments"],
queryFn: async () => {
- const response = await fetch(apiEndpoint + "/filament");
+ const response = await fetch(getAPIURL() + "/filament");
if (!response.ok) {
throw new Error("Network response was not ok");
}
@@ -115,12 +114,11 @@ export function useSpoolmanFilamentNames(enabled: boolean = false) {
}
export function useSpoolmanVendors(enabled: boolean = false) {
- const apiEndpoint = import.meta.env.VITE_APIURL;
return useQuery({
enabled: enabled,
queryKey: ["vendors"],
queryFn: async () => {
- const response = await fetch(apiEndpoint + "/vendor");
+ const response = await fetch(getAPIURL() + "/vendor");
if (!response.ok) {
throw new Error("Network response was not ok");
}
@@ -137,12 +135,11 @@ export function useSpoolmanVendors(enabled: boolean = false) {
}
export function useSpoolmanMaterials(enabled: boolean = false) {
- const apiEndpoint = import.meta.env.VITE_APIURL;
return useQuery({
enabled: enabled,
queryKey: ["materials"],
queryFn: async () => {
- const response = await fetch(apiEndpoint + "/material");
+ const response = await fetch(getAPIURL() + "/material");
if (!response.ok) {
throw new Error("Network response was not ok");
}
@@ -155,12 +152,11 @@ export function useSpoolmanMaterials(enabled: boolean = false) {
}
export function useSpoolmanArticleNumbers(enabled: boolean = false) {
- const apiEndpoint = import.meta.env.VITE_APIURL;
return useQuery({
enabled: enabled,
queryKey: ["articleNumbers"],
queryFn: async () => {
- const response = await fetch(apiEndpoint + "/article-number");
+ const response = await fetch(getAPIURL() + "/article-number");
if (!response.ok) {
throw new Error("Network response was not ok");
}
@@ -173,12 +169,11 @@ export function useSpoolmanArticleNumbers(enabled: boolean = false) {
}
export function useSpoolmanLotNumbers(enabled: boolean = false) {
- const apiEndpoint = import.meta.env.VITE_APIURL;
return useQuery({
enabled: enabled,
queryKey: ["lotNumbers"],
queryFn: async () => {
- const response = await fetch(apiEndpoint + "/lot-number");
+ const response = await fetch(getAPIURL() + "/lot-number");
if (!response.ok) {
throw new Error("Network response was not ok");
}
@@ -191,12 +186,11 @@ export function useSpoolmanLotNumbers(enabled: boolean = false) {
}
export function useSpoolmanLocations(enabled: boolean = false) {
- const apiEndpoint = import.meta.env.VITE_APIURL;
return useQuery({
enabled: enabled,
queryKey: ["locations"],
queryFn: async () => {
- const response = await fetch(apiEndpoint + "/location");
+ const response = await fetch(getAPIURL() + "/location");
if (!response.ok) {
throw new Error("Network response was not ok");
}
diff --git a/client/src/components/version.tsx b/client/src/components/version.tsx
index 9bf6352..fb51d80 100644
--- a/client/src/components/version.tsx
+++ b/client/src/components/version.tsx
@@ -1,5 +1,6 @@
import { useQuery } from "@tanstack/react-query";
import { Spin, Typography } from "antd";
+import { getAPIURL } from "../utils/url";
const { Text } = Typography;
@@ -15,12 +16,10 @@ interface IInfo {
}
export const Version: React.FC = () => {
- const apiEndpoint = import.meta.env.VITE_APIURL;
-
const infoResult = useQuery({
queryKey: ["info"],
queryFn: async () => {
- const response = await fetch(apiEndpoint + "/info");
+ const response = await fetch(getAPIURL() + "/info");
if (!response.ok) {
throw new Error("Network response was not ok");
}
diff --git a/client/src/i18n.ts b/client/src/i18n.ts
index 317096e..9d8cbe5 100644
--- a/client/src/i18n.ts
+++ b/client/src/i18n.ts
@@ -2,6 +2,7 @@ import i18n from "i18next";
import detector from "i18next-browser-languagedetector";
import Backend from "i18next-xhr-backend";
import { initReactI18next } from "react-i18next";
+import { getBasePath } from "./utils/url";
interface Language {
name: string;
@@ -106,7 +107,7 @@ i18n
.init({
supportedLngs: Object.keys(languages),
backend: {
- loadPath: "/locales/{{lng}}/{{ns}}.json",
+ loadPath: getBasePath() + "/locales/{{lng}}/{{ns}}.json",
},
defaultNS: "common",
fallbackLng: "en",
diff --git a/client/src/pages/spools/functions.ts b/client/src/pages/spools/functions.ts
index e6da3d4..1ba9092 100644
--- a/client/src/pages/spools/functions.ts
+++ b/client/src/pages/spools/functions.ts
@@ -1,7 +1,7 @@
+import { getAPIURL } from "../../utils/url";
import { ISpool } from "./model";
export async function setSpoolArchived(spool: ISpool, archived: boolean) {
- const apiEndpoint = import.meta.env.VITE_APIURL;
const init: RequestInit = {
method: "PATCH",
headers: {
@@ -11,6 +11,6 @@ export async function setSpoolArchived(spool: ISpool, archived: boolean) {
archived: archived,
}),
};
- const request = new Request(apiEndpoint + "/spool/" + spool.id);
+ const request = new Request(getAPIURL() + "/spool/" + spool.id);
await fetch(request, init);
}
diff --git a/client/src/utils/queryFields.ts b/client/src/utils/queryFields.ts
index d569278..9c106c8 100644
--- a/client/src/utils/queryFields.ts
+++ b/client/src/utils/queryFields.ts
@@ -1,5 +1,6 @@
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import dayjs from "dayjs";
+import { getAPIURL } from "./url";
export enum FieldType {
text = "text",
@@ -34,11 +35,10 @@ export interface Field extends FieldParameters {
}
export function useGetFields(entity_type: EntityType) {
- const apiEndpoint = import.meta.env.VITE_APIURL;
return useQuery({
queryKey: ["fields", entity_type],
queryFn: async () => {
- const response = await fetch(`${apiEndpoint}/field/${entity_type}`);
+ const response = await fetch(`${getAPIURL()}/field/${entity_type}`);
return response.json();
},
});
@@ -47,10 +47,9 @@ export function useGetFields(entity_type: EntityType) {
export function useSetField(entity_type: EntityType) {
const queryClient = useQueryClient();
- const apiEndpoint = import.meta.env.VITE_APIURL;
return useMutation({
mutationFn: async ({ key, params }) => {
- const response = await fetch(`${apiEndpoint}/field/${entity_type}/${key}`, {
+ const response = await fetch(`${getAPIURL()}/field/${entity_type}/${key}`, {
method: "POST",
headers: {
"Content-Type": "application/json",
@@ -110,10 +109,9 @@ export function useSetField(entity_type: EntityType) {
export function useDeleteField(entity_type: EntityType) {
const queryClient = useQueryClient();
- const apiEndpoint = import.meta.env.VITE_APIURL;
return useMutation({
mutationFn: async (key) => {
- const response = await fetch(`${apiEndpoint}/field/${entity_type}/${key}`, {
+ const response = await fetch(`${getAPIURL()}/field/${entity_type}/${key}`, {
method: "DELETE",
});
diff --git a/client/src/utils/querySettings.ts b/client/src/utils/querySettings.ts
index 87b8ade..dc5b1b8 100644
--- a/client/src/utils/querySettings.ts
+++ b/client/src/utils/querySettings.ts
@@ -1,4 +1,5 @@
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
+import { getAPIURL } from "./url";
interface SettingResponseValue {
value: string;
@@ -11,22 +12,20 @@ interface SettingsResponse {
}
export function useGetSettings() {
- const apiEndpoint = import.meta.env.VITE_APIURL;
return useQuery({
queryKey: ["settings"],
queryFn: async () => {
- const response = await fetch(`${apiEndpoint}/setting`);
+ const response = await fetch(`${getAPIURL()}/setting/`);
return response.json();
},
});
}
export function useGetSetting(key: string) {
- const apiEndpoint = import.meta.env.VITE_APIURL;
return useQuery({
queryKey: ["settings", key],
queryFn: async () => {
- const response = await fetch(`${apiEndpoint}/setting/${key}`);
+ const response = await fetch(`${getAPIURL()}/setting/${key}`);
return response.json();
},
});
@@ -35,10 +34,9 @@ export function useGetSetting(key: string) {
export function useSetSetting() {
const queryClient = useQueryClient();
- const apiEndpoint = import.meta.env.VITE_APIURL;
return useMutation({
mutationFn: async ({ key, value }) => {
- const response = await fetch(`${apiEndpoint}/setting/${key}`, {
+ const response = await fetch(`${getAPIURL()}/setting/${key}`, {
method: "POST",
headers: {
"Content-Type": "application/json",
diff --git a/client/src/utils/url.ts b/client/src/utils/url.ts
new file mode 100644
index 0000000..ba638dd
--- /dev/null
+++ b/client/src/utils/url.ts
@@ -0,0 +1,35 @@
+declare global {
+ interface Window {
+ SPOOLMAN_BASE_PATH: string;
+ }
+}
+
+/**
+ * Returns the base path of the application.
+ *
+ * If a base path is set, this returns e.g. "/spoolman". If none is set, it returns "".
+ *
+ * @return {string} The base path of the application. If the `SPOOLMAN_BASE_PATH`
+ * window variable is set and not empty, it is returned. Otherwise, the
+ * default base path "" is returned.
+ */
+export function getBasePath(): string {
+ if (window.SPOOLMAN_BASE_PATH && window.SPOOLMAN_BASE_PATH.length > 0) {
+ return window.SPOOLMAN_BASE_PATH;
+ } else {
+ return "";
+ }
+}
+
+/**
+ * A function that returns the Spoolman API URL
+ * This returns e.g. "/spoolman/api/v1" if the base path is "/spoolman"
+ *
+ * @return {string} The API URL
+ */
+export function getAPIURL(): string {
+ if (!import.meta.env.VITE_APIURL) {
+ throw new Error("VITE_APIURL is not set");
+ }
+ return getBasePath() + import.meta.env.VITE_APIURL;
+}
diff --git a/client/vite.config.ts b/client/vite.config.ts
index 6335a4d..5ba6dc9 100644
--- a/client/vite.config.ts
+++ b/client/vite.config.ts
@@ -4,5 +4,6 @@ import svgr from "vite-plugin-svgr";
export default defineConfig({
+ base: '',
plugins: [react(), svgr()],
});
diff --git a/spoolman/client.py b/spoolman/client.py
index 3964813..154aafd 100644
--- a/spoolman/client.py
+++ b/spoolman/client.py
@@ -2,24 +2,37 @@
# ruff: noqa: PTH118
+import logging
import os
+from pathlib import Path
from typing import Union
from fastapi.staticfiles import StaticFiles
+logger = logging.getLogger(__name__)
+
class SinglePageApplication(StaticFiles):
"""Serve a single page application."""
- def __init__(self, directory: str) -> None:
+ def __init__(self, directory: str, base_path: str) -> None:
"""Construct."""
super().__init__(directory=directory, packages=None, html=True, check_dir=True)
+ self.base_path = base_path.removeprefix("/")
def lookup_path(self, path: str) -> tuple[str, Union[os.stat_result, None]]:
"""Return index.html if the requested file cannot be found."""
+ path = path.removeprefix(self.base_path).removeprefix("/")
+
full_path, stat_result = super().lookup_path(path)
if stat_result is None:
+ ext = Path(path).suffix
+ # Check if user is looking for some specific non-document file
+ if len(ext) > 1 and ext != ".html":
+ # If so, return 404
+ return ("", None)
+ # Otherwise, they did look for a document, lead them to index.html
return super().lookup_path("index.html")
return (full_path, stat_result)
diff --git a/spoolman/env.py b/spoolman/env.py
index d9bc182..a5db3e0 100644
--- a/spoolman/env.py
+++ b/spoolman/env.py
@@ -398,3 +398,19 @@ def is_metrics_enabled() -> bool:
raise ValueError(
f"Failed to parse SPOOLMAN_METRICS_ENABLED variable: Unknown metrics enabled '{metrics_enabled}'.",
)
+
+
+def get_base_path() -> str:
+ """Get the base path.
+
+ This is formated so that it always starts with a /, and does not end with a /
+
+ Returns:
+ str: The base path.
+ """
+ path = os.getenv("SPOOLMAN_BASE_PATH", "")
+ if len(path) == 0:
+ return ""
+
+ # Ensure it starts with / and does not end with /
+ return "/" + path.strip("/")
diff --git a/spoolman/main.py b/spoolman/main.py
index 406655e..2080b7a 100644
--- a/spoolman/main.py
+++ b/spoolman/main.py
@@ -1,4 +1,5 @@
"""Main entrypoint to the server."""
+
import logging
import subprocess
from logging.handlers import TimedRotatingFileHandler
@@ -8,7 +9,7 @@ import uvicorn
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.gzip import GZipMiddleware
-from fastapi.responses import PlainTextResponse
+from fastapi.responses import PlainTextResponse, RedirectResponse, Response
from prometheus_client import generate_latest
from scheduler.asyncio.scheduler import Scheduler
@@ -38,12 +39,12 @@ app = FastAPI(
version=env.get_version(),
)
app.add_middleware(GZipMiddleware)
-app.mount("/api/v1", v1_app)
+app.mount(env.get_base_path() + "/api/v1", v1_app)
# WA for prometheus /metrics bind with SinglePageApp at root
@app.get(
- "/metrics",
+ env.get_base_path() + "/metrics",
response_class=PlainTextResponse,
name="Get metrics for prometheus",
description=(
@@ -55,8 +56,36 @@ def get_metrics() -> bytes:
return generate_latest(registry)
-app.mount("", app=SinglePageApplication(directory="client/dist"))
+base_path = env.get_base_path()
+if base_path != "":
+ logger.info("Base path is: %s", base_path)
+ # If base path is set, add a redirect from non-slash suffix to slash
+ # suffix. Otherwise it won't work.
+ @app.get(base_path)
+ def root_redirect() -> Response:
+ """Redirect to base path."""
+ return RedirectResponse(base_path + "/")
+
+
+# Return a dynamic js config file
+# This is so that the client side can access the base path variable.
+@app.get(env.get_base_path() + "/config.js")
+def get_configjs() -> Response:
+ """Return a dynamic js config file."""
+ if '"' in base_path:
+ raise ValueError("Base path contains quotes, which are not allowed.")
+
+ return Response(
+ content=f"""
+window.SPOOLMAN_BASE_PATH = "{base_path}";
+""",
+ media_type="text/javascript",
+ )
+
+
+# Mount the client side app
+app.mount(base_path, app=SinglePageApplication(directory="client/dist", base_path=env.get_base_path()))
# Allow all origins if in debug mode
if env.is_debug_mode():