diff --git a/.dockerignore b/.dockerignore index b461b8d7..cd04d110 100644 --- a/.dockerignore +++ b/.dockerignore @@ -12,3 +12,6 @@ __pycache__/ *.pyc *.pyd *.pyo + +node_modules/ +package-lock.json diff --git a/.github/workflows/setup.sh b/.github/workflows/setup.sh index 6731e824..e61926cd 100755 --- a/.github/workflows/setup.sh +++ b/.github/workflows/setup.sh @@ -10,7 +10,7 @@ echo -e '[arcanisrepo]\nServer = https://repo.arcanis.me/$arch\nSigLevel = Never # refresh the image pacman -Syyu --noconfirm # main dependencies -pacman -S --noconfirm devtools git pyalpm python-bcrypt python-filelock python-inflection python-pyelftools python-requests python-systemd sudo +pacman -S --noconfirm devtools git npm pyalpm python-bcrypt python-filelock python-inflection python-pyelftools python-requests python-systemd sudo # make dependencies pacman -S --noconfirm --asdeps base-devel python-build python-flit python-installer python-tox python-wheel # optional dependencies diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 57781a0c..2ad62ad0 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -26,7 +26,7 @@ jobs: - ${{ github.workspace }}:/build steps: - - run: pacman --noconfirm -Syu base-devel git python-tox + - run: pacman --noconfirm -Syu base-devel git npm python-tox - run: git config --global --add safe.directory * diff --git a/.gitignore b/.gitignore index 1fa4cc9d..5a856dcf 100644 --- a/.gitignore +++ b/.gitignore @@ -99,3 +99,9 @@ status_cache.json *.db docs/html/ + +# Frontend +node_modules/ +package-lock.json +package/share/ahriman/templates/static/index.js +package/share/ahriman/templates/static/index.css diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 74981a72..9f693d1d 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -125,7 +125,7 @@ Again, the most checks can be performed by `tox` command, though some additional def __hash__(self) -> int: ... # basically any magic (or look-alike) method ``` - Methods inside one group should be ordered alphabetically, the only exceptions are `__init__` (`__post_init__` for dataclasses), `__new__` and `__del__` methods which should be defined first. For test methods it is recommended to follow the order in which functions are defined. + Methods inside one group should be ordered alphabetically, the only exceptions are `__init__` (`__post_init__` for dataclasses), `__new__` and `__del__` methods which should be defined first. For test methods it is recommended to follow the order in which functions are defined. Same idea applies to frontend classes. Though, we would like to highlight abstract methods (i.e. ones which raise `NotImplementedError`), we still keep in global order at the moment. @@ -172,8 +172,9 @@ Again, the most checks can be performed by `tox` command, though some additional ) ``` -* One file should define only one class, exception is class satellites in case if file length remains less than 400 lines. -* It is possible to create file which contains some functions (e.g. `ahriman.core.util`), but in this case you would need to define `__all__` attribute. +* Imports goes in alphabetical order, no relative imports allowed. Same rule applies to frontend classes. +* One file should define only one class, exception is class satellites in case if file length remains less than 400 lines. Same rule applies to frontend classes. +* It is possible to create file which contains some functions (e.g. `ahriman.core.utils`), but in this case you would need to define `__all__` attribute. * The file size mentioned above must be applicable in general. In case of big classes consider splitting them into traits. Note, however, that `pylint` includes comments and docstrings into counter, thus you need to check file size by other tools. * No global variable is allowed outside of `ahriman` module. `ahriman.core.context` is also special case. * Single quotes are not allowed. The reason behind this restriction is the fact that docstrings must be written by using double quotes only, and we would like to make style consistent. @@ -226,6 +227,8 @@ Again, the most checks can be performed by `tox` command, though some additional The projects also uses typing checks (provided by `mypy`) and some linter checks provided by `pylint` and `bandit`. Those checks must be passed successfully for any open pull requests. +Frontend checks normally are performed by `eslint` (e.g. `npx run eslint`). + ## Developers how to ### Run automated checks diff --git a/docker/Dockerfile b/docker/Dockerfile index fa5eed5c..061f9ff9 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -23,6 +23,7 @@ COPY "docker/install-aur-package.sh" "/usr/local/bin/install-aur-package" RUN pacman -S --noconfirm --asdeps \ devtools \ git \ + npm \ pyalpm \ python-bcrypt \ python-filelock \ diff --git a/docs/ahriman.web.rst b/docs/ahriman.web.rst index c175f4ac..3164f3f4 100644 --- a/docs/ahriman.web.rst +++ b/docs/ahriman.web.rst @@ -39,6 +39,14 @@ ahriman.web.routes module :no-undoc-members: :show-inheritance: +ahriman.web.server\_info module +------------------------------- + +.. automodule:: ahriman.web.server_info + :members: + :no-undoc-members: + :show-inheritance: + ahriman.web.web module ---------------------- diff --git a/docs/ahriman.web.schemas.rst b/docs/ahriman.web.schemas.rst index 1900afaf..425ae914 100644 --- a/docs/ahriman.web.schemas.rst +++ b/docs/ahriman.web.schemas.rst @@ -20,6 +20,14 @@ ahriman.web.schemas.aur\_package\_schema module :no-undoc-members: :show-inheritance: +ahriman.web.schemas.auth\_info\_schema module +--------------------------------------------- + +.. automodule:: ahriman.web.schemas.auth_info_schema + :members: + :no-undoc-members: + :show-inheritance: + ahriman.web.schemas.auth\_schema module --------------------------------------- @@ -28,6 +36,14 @@ ahriman.web.schemas.auth\_schema module :no-undoc-members: :show-inheritance: +ahriman.web.schemas.auto\_refresh\_interval\_schema module +---------------------------------------------------------- + +.. automodule:: ahriman.web.schemas.auto_refresh_interval_schema + :members: + :no-undoc-members: + :show-inheritance: + ahriman.web.schemas.build\_options\_schema module ------------------------------------------------- @@ -108,6 +124,14 @@ ahriman.web.schemas.info\_schema module :no-undoc-members: :show-inheritance: +ahriman.web.schemas.info\_v2\_schema module +------------------------------------------- + +.. automodule:: ahriman.web.schemas.info_v2_schema + :members: + :no-undoc-members: + :show-inheritance: + ahriman.web.schemas.internal\_status\_schema module --------------------------------------------------- diff --git a/docs/ahriman.web.views.v2.rst b/docs/ahriman.web.views.v2.rst index 0d06409a..f5e97f6c 100644 --- a/docs/ahriman.web.views.v2.rst +++ b/docs/ahriman.web.views.v2.rst @@ -8,6 +8,7 @@ Subpackages :maxdepth: 4 ahriman.web.views.v2.packages + ahriman.web.views.v2.status Module contents --------------- diff --git a/docs/ahriman.web.views.v2.status.rst b/docs/ahriman.web.views.v2.status.rst new file mode 100644 index 00000000..65174688 --- /dev/null +++ b/docs/ahriman.web.views.v2.status.rst @@ -0,0 +1,21 @@ +ahriman.web.views.v2.status package +=================================== + +Submodules +---------- + +ahriman.web.views.v2.status.info module +--------------------------------------- + +.. automodule:: ahriman.web.views.v2.status.info + :members: + :no-undoc-members: + :show-inheritance: + +Module contents +--------------- + +.. automodule:: ahriman.web.views.v2.status + :members: + :no-undoc-members: + :show-inheritance: diff --git a/docs/configuration.rst b/docs/configuration.rst index 71446cc6..2b11d3a8 100644 --- a/docs/configuration.rst +++ b/docs/configuration.rst @@ -118,7 +118,6 @@ Base authorization settings. ``OAuth`` provider requires ``aioauth-client`` libr * ``cookie_secret_key`` - secret key which will be used for cookies encryption, string, optional. It must be 32 bytes URL-safe base64-encoded and can be generated as following ``base64.urlsafe_b64encode(os.urandom(32)).decode("utf8")``. If not set, it will be generated automatically; note, however, that in this case, all sessions will be automatically invalidated during the service restart. * ``full_access_group`` - name of the secondary group (e.g. ``wheel``) to be used as admin group in the service, string, required in case if ``pam`` is used. * ``max_age`` - parameter which controls both cookie expiration and token expiration inside the service in seconds, integer, optional, default is 7 days. -* ``oauth_icon`` - OAuth2 login button icon, string, optional, default is ``google``. Must be valid `Bootstrap icon `__ name. * ``oauth_provider`` - OAuth2 provider class name as is in ``aioauth-client`` (e.g. ``GoogleClient``, ``GithubClient`` etc), string, required in case if ``oauth`` is used. * ``oauth_scopes`` - scopes list for OAuth2 provider, which will allow retrieving user email (which is used for checking user permissions), e.g. ``https://www.googleapis.com/auth/userinfo.email`` for ``GoogleClient`` or ``user:email`` for ``GithubClient``, space separated list of strings, required in case if ``oauth`` is used. * ``permit_root_login`` - allow login as root user, boolean, optional, default ``no``. @@ -188,6 +187,7 @@ Web server settings. This feature requires ``aiohttp`` libraries to be installed * ``port`` - port to bind, integer, optional. * ``service_only`` - disable status routes (including logs), boolean, optional, default ``no``. * ``static_path`` - path to directory with static files, string, required. +* ``template`` - Jinja2 template name for the index page, string, optional, default ``build-status.jinja2``. * ``templates`` - path to templates directories, space separated list of paths, required. * ``unix_socket`` - path to the listening unix socket, string, optional. If set, server will create the socket on the specified address which can (and will) be used by application. Note, that unlike usual host/port configuration, unix socket allows to perform requests without authorization. * ``unix_socket_unsafe`` - set unsafe (o+w) permissions to unix socket, boolean, optional, default ``yes``. This option is enabled by default, because it is supposed that unix socket is created in safe environment (only web service is supposed to be used in unsafe), but it can be disabled by configuration. diff --git a/frontend/eslint.config.js b/frontend/eslint.config.js new file mode 100644 index 00000000..94c510ab --- /dev/null +++ b/frontend/eslint.config.js @@ -0,0 +1,67 @@ +import js from "@eslint/js"; +import stylistic from "@stylistic/eslint-plugin"; +import reactHooks from "eslint-plugin-react-hooks"; +import reactRefresh from "eslint-plugin-react-refresh"; +import simpleImportSort from "eslint-plugin-simple-import-sort"; +import tseslint from "typescript-eslint"; + +export default tseslint.config( + { ignores: ["dist"] }, + { + extends: [js.configs.recommended, ...tseslint.configs.recommendedTypeChecked], + files: ["src/**/*.{ts,tsx}"], + languageOptions: { + parserOptions: { + projectService: true, + tsconfigRootDir: import.meta.dirname, + }, + }, + plugins: { + "react-hooks": reactHooks, + "react-refresh": reactRefresh, + "simple-import-sort": simpleImportSort, + "@stylistic": stylistic, + }, + rules: { + ...reactHooks.configs.recommended.rules, + "react-refresh/only-export-components": ["warn", { allowConstantExport: true }], + + // imports + "simple-import-sort/imports": "error", + "simple-import-sort/exports": "error", + + // brackets + "curly": "error", + "@stylistic/brace-style": ["error", "1tbs"], + + // stylistic + "@stylistic/array-bracket-spacing": ["error", "never"], + "@stylistic/arrow-parens": ["error", "as-needed"], + "@stylistic/comma-dangle": ["error", "always-multiline"], + "@stylistic/comma-spacing": ["error", { before: false, after: true }], + "@stylistic/eol-last": ["error", "always"], + "@stylistic/indent": ["error", 4], + "@stylistic/jsx-quotes": ["error", "prefer-double"], + "@stylistic/max-len": ["error", { + code: 120, + ignoreComments: true, + ignoreStrings: true, + ignoreTemplateLiterals: true, + ignoreUrls: true, + }], + "@stylistic/no-extra-parens": ["error", "all"], + "@stylistic/no-multi-spaces": "error", + "@stylistic/no-multiple-empty-lines": ["error", { max: 1 }], + "@stylistic/no-trailing-spaces": "error", + "@stylistic/object-curly-spacing": ["error", "always"], + "@stylistic/quotes": ["error", "double"], + "@stylistic/semi": ["error", "always"], + + // typescript + "@typescript-eslint/consistent-type-imports": ["error", { prefer: "type-imports" }], + "@typescript-eslint/explicit-function-return-type": ["error", { allowExpressions: true }], + "@typescript-eslint/no-deprecated": "error", + "@typescript-eslint/no-unused-vars": ["error", { argsIgnorePattern: "^_" }], + }, + }, +); diff --git a/frontend/index.html b/frontend/index.html new file mode 100644 index 00000000..7246ce66 --- /dev/null +++ b/frontend/index.html @@ -0,0 +1,16 @@ + + + + + + ahriman + + + + + +
+ + + + diff --git a/frontend/package.json b/frontend/package.json new file mode 100644 index 00000000..6033833a --- /dev/null +++ b/frontend/package.json @@ -0,0 +1,42 @@ +{ + "name": "ahriman-frontend", + "private": true, + "type": "module", + "version": "2.20.0-rc4", + "scripts": { + "build": "tsc && vite build", + "dev": "vite", + "lint": "eslint src/", + "lint:fix": "eslint --fix src/", + "preview": "vite preview" + }, + "dependencies": { + "@emotion/react": "^11.11.0", + "@emotion/styled": "^11.11.0", + "@mui/icons-material": "^7.3.8", + "@mui/material": "^7.3.8", + "@mui/x-data-grid": "^8.27.3", + "@tanstack/react-query": "^5.0.0", + "chart.js": "^4.5.0", + "react": "^19.2.4", + "react-chartjs-2": "^5.2.0", + "react-dom": "^19.2.4", + "react-syntax-highlighter": "^16.1.1" + }, + "devDependencies": { + "@eslint/js": "^9.39.3", + "@stylistic/eslint-plugin": "^5.9.0", + "@types/react": "^19.2.14", + "@types/react-dom": "^19.2.3", + "@types/react-syntax-highlighter": "^15.5.13", + "@vitejs/plugin-react": "^5.0.0", + "eslint": "^9.39.3", + "eslint-plugin-react-hooks": "^7.0.1", + "eslint-plugin-react-refresh": "^0.5.2", + "eslint-plugin-simple-import-sort": "^12.1.1", + "typescript": "^5.3.0", + "typescript-eslint": "^8.56.1", + "vite": "^7.3.1", + "vite-tsconfig-paths": "^6.1.1" + } +} diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx new file mode 100644 index 00000000..7ec3be07 --- /dev/null +++ b/frontend/src/App.tsx @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2021-2026 ahriman team. + * + * This file is part of ahriman + * (see https://github.com/arcan1s/ahriman). + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +import CssBaseline from "@mui/material/CssBaseline"; +import { ThemeProvider } from "@mui/material/styles"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import AppLayout from "components/layout/AppLayout"; +import { AuthProvider } from "contexts/AuthProvider"; +import { ClientProvider } from "contexts/ClientProvider"; +import { NotificationProvider } from "contexts/NotificationProvider"; +import { RepositoryProvider } from "contexts/RepositoryProvider"; +import type React from "react"; +import Theme from "theme/Theme"; + +const queryClient = new QueryClient({ + defaultOptions: { + queries: { + staleTime: 30_000, + retry: 1, + }, + }, +}); + +export default function App(): React.JSX.Element { + return ( + + + + + + + + + + + + + + + ); +} diff --git a/frontend/src/api/client/AhrimanClient.ts b/frontend/src/api/client/AhrimanClient.ts new file mode 100644 index 00000000..ff2275ff --- /dev/null +++ b/frontend/src/api/client/AhrimanClient.ts @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2021-2026 ahriman team. + * + * This file is part of ahriman + * (see https://github.com/arcan1s/ahriman). + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +import { Client } from "api/client/Client"; +import { FetchClient } from "api/client/FetchClient"; +import { ServiceClient } from "api/client/ServiceClient"; +import type { LoginRequest } from "models/LoginRequest"; + +export class AhrimanClient { + + protected client = new Client(); + + readonly fetch = new FetchClient(this.client); + readonly service = new ServiceClient(this.client); + + async login(data: LoginRequest): Promise { + return this.client.request("/api/v1/login", { method: "POST", json: data }); + } + + async logout(): Promise { + return this.client.request("/api/v1/logout", { method: "POST" }); + } +} diff --git a/frontend/src/api/client/ApiError.ts b/frontend/src/api/client/ApiError.ts new file mode 100644 index 00000000..1462d48b --- /dev/null +++ b/frontend/src/api/client/ApiError.ts @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2021-2026 ahriman team. + * + * This file is part of ahriman + * (see https://github.com/arcan1s/ahriman). + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +export class ApiError extends Error { + status: number; + statusText: string; + body: string; + + constructor(status: number, statusText: string, body: string) { + super(`${status} ${statusText}`); + this.status = status; + this.statusText = statusText; + this.body = body; + } + + get detail(): string { + try { + const parsed = JSON.parse(this.body) as Record; + return parsed.error ?? (this.body || this.message); + } catch { + return this.body || this.message; + } + } + + static errorDetail(exception: unknown): string { + return exception instanceof ApiError ? exception.detail : String(exception); + } +} diff --git a/frontend/src/api/client/Client.ts b/frontend/src/api/client/Client.ts new file mode 100644 index 00000000..e305c28b --- /dev/null +++ b/frontend/src/api/client/Client.ts @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2021-2026 ahriman team. + * + * This file is part of ahriman + * (see https://github.com/arcan1s/ahriman). + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +import { ApiError } from "api/client/ApiError"; +import type { RequestOptions } from "api/client/RequestOptions"; + +export class Client { + + async request(url: string, options: RequestOptions = {}): Promise { + const { method, query, json } = options; + + let fullUrl = url; + if (query) { + const params = new URLSearchParams(); + for (const [key, value] of Object.entries(query)) { + if (value !== undefined && value !== null) { + params.set(key, String(value)); + } + } + fullUrl += `?${params.toString()}`; + } + + const headers: Record = { + Accept: "application/json", + }; + if (json !== undefined) { + headers["Content-Type"] = "application/json"; + } + + const requestInit: RequestInit = { + method: method || (json ? "POST" : "GET"), + headers, + }; + + if (json !== undefined) { + requestInit.body = JSON.stringify(json); + } + + const response = await fetch(fullUrl, requestInit); + + if (!response.ok) { + const body = await response.text(); + throw new ApiError(response.status, response.statusText, body); + } + + const contentType = response.headers.get("Content-Type") ?? ""; + if (contentType.includes("application/json")) { + return await response.json() as T; + } + return await response.text() as T; + } +} diff --git a/frontend/src/api/client/FetchClient.ts b/frontend/src/api/client/FetchClient.ts new file mode 100644 index 00000000..28de08c3 --- /dev/null +++ b/frontend/src/api/client/FetchClient.ts @@ -0,0 +1,109 @@ +/* + * Copyright (c) 2021-2026 ahriman team. + * + * This file is part of ahriman + * (see https://github.com/arcan1s/ahriman). + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +import type { Client } from "api/client/Client"; +import type { Changes } from "models/Changes"; +import type { Dependencies } from "models/Dependencies"; +import type { Event } from "models/Event"; +import type { InfoResponse } from "models/InfoResponse"; +import type { InternalStatus } from "models/InternalStatus"; +import type { LogRecord } from "models/LogRecord"; +import type { PackageStatus } from "models/PackageStatus"; +import type { Patch } from "models/Patch"; +import { RepositoryId } from "models/RepositoryId"; + +export class FetchClient { + + protected client: Client; + + constructor(client: Client) { + this.client = client; + } + + async fetchPackage(packageBase: string, repository: RepositoryId): Promise { + return this.client.request(`/api/v1/packages/${encodeURIComponent(packageBase)}`, { + query: repository.toQuery(), + }); + } + + async fetchPackageChanges(packageBase: string, repository: RepositoryId): Promise { + return this.client.request(`/api/v1/packages/${encodeURIComponent(packageBase)}/changes`, { + query: repository.toQuery(), + }); + } + + async fetchPackageDependencies(packageBase: string, repository: RepositoryId): Promise { + return this.client.request(`/api/v1/packages/${encodeURIComponent(packageBase)}/dependencies`, { + query: repository.toQuery(), + }); + } + + async fetchPackageEvents(repository: RepositoryId, objectId?: string, limit?: number): Promise { + const query: Record = repository.toQuery(); + if (objectId) { + query.object_id = objectId; + } + if (limit) { + query.limit = limit; + } + return this.client.request("/api/v1/events", { query }); + } + + async fetchPackageLogs( + packageBase: string, + repository: RepositoryId, + version?: string, + processId?: string, + head?: boolean, + ): Promise { + const query: Record = { ...repository.toQuery() }; + if (version) { + query.version = version; + } + if (processId) { + query.process_id = processId; + } + if (head) { + query.head = true; + } + return this.client.request(`/api/v2/packages/${encodeURIComponent(packageBase)}/logs`, { query }); + } + + async fetchPackagePatches(packageBase: string): Promise { + return this.client.request(`/api/v1/packages/${encodeURIComponent(packageBase)}/patches`); + } + + async fetchPackages(repository: RepositoryId): Promise { + return this.client.request("/api/v1/packages", { query: repository.toQuery() }); + } + + async fetchServerInfo(): Promise { + const info = await this.client.request("/api/v2/info"); + return { + ...info, + repositories: info.repositories.map(repo => + new RepositoryId(repo.architecture, repo.repository), + ), + }; + } + + async fetchServerStatus(repository: RepositoryId): Promise { + return this.client.request("/api/v1/status", { query: repository.toQuery() }); + } +} diff --git a/frontend/src/api/client/RequestOptions.ts b/frontend/src/api/client/RequestOptions.ts new file mode 100644 index 00000000..ae4f3f8b --- /dev/null +++ b/frontend/src/api/client/RequestOptions.ts @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2021-2026 ahriman team. + * + * This file is part of ahriman + * (see https://github.com/arcan1s/ahriman). + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +export interface RequestOptions { + method?: string; + query?: Record; + json?: unknown; +} diff --git a/frontend/src/api/client/ServiceClient.ts b/frontend/src/api/client/ServiceClient.ts new file mode 100644 index 00000000..21006840 --- /dev/null +++ b/frontend/src/api/client/ServiceClient.ts @@ -0,0 +1,88 @@ +/* + * Copyright (c) 2021-2026 ahriman team. + * + * This file is part of ahriman + * (see https://github.com/arcan1s/ahriman). + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +import type { Client } from "api/client/Client"; +import type { AURPackage } from "models/AURPackage"; +import type { PackageActionRequest } from "models/PackageActionRequest"; +import type { PGPKey } from "models/PGPKey"; +import type { PGPKeyRequest } from "models/PGPKeyRequest"; +import type { RepositoryId } from "models/RepositoryId"; + +export class ServiceClient { + + protected client: Client; + + constructor(client: Client) { + this.client = client; + } + + async servicePackageAdd(repository: RepositoryId, data: PackageActionRequest): Promise { + return this.client.request("/api/v1/service/add", { method: "POST", query: repository.toQuery(), json: data }); + } + + async servicePackagePatchRemove(packageBase: string, key: string): Promise { + return this.client.request(`/api/v1/packages/${encodeURIComponent(packageBase)}/patches/${encodeURIComponent(key)}`, { + method: "DELETE", + }); + } + + async servicePackageRemove(repository: RepositoryId, packages: string[]): Promise { + return this.client.request("/api/v1/service/remove", { + method: "POST", + query: repository.toQuery(), + json: { packages }, + }); + } + + async servicePackageRequest(repository: RepositoryId, data: PackageActionRequest): Promise { + return this.client.request("/api/v1/service/request", { + method: "POST", + query: repository.toQuery(), + json: data, + }); + } + + async servicePackageSearch(query: string): Promise { + return this.client.request("/api/v1/service/search", { query: { for: query } }); + } + + async servicePackageUpdate(repository: RepositoryId, data: PackageActionRequest): Promise { + return this.client.request("/api/v1/service/update", { + method: "POST", + query: repository.toQuery(), + json: data, + }); + } + + async servicePGPFetch(key: string, server: string): Promise { + return this.client.request("/api/v1/service/pgp", { query: { key, server } }); + } + + async servicePGPImport(data: PGPKeyRequest): Promise { + return this.client.request("/api/v1/service/pgp", { method: "POST", json: data }); + } + + async serviceRebuild(repository: RepositoryId, packages: string[]): Promise { + return this.client.request("/api/v1/service/rebuild", { + method: "POST", + query: repository.toQuery(), + json: { packages }, + }); + } +} diff --git a/frontend/src/chartSetup.ts b/frontend/src/chartSetup.ts new file mode 100644 index 00000000..f2463226 --- /dev/null +++ b/frontend/src/chartSetup.ts @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2021-2026 ahriman team. + * + * This file is part of ahriman + * (see https://github.com/arcan1s/ahriman). + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +import { + ArcElement, + BarElement, + CategoryScale, + Chart as ChartJS, + Legend, + LinearScale, + LineElement, + PointElement, + Tooltip, +} from "chart.js"; + +ChartJS.register( + ArcElement, + BarElement, + CategoryScale, + Legend, + LinearScale, + LineElement, + PointElement, + Tooltip, +); diff --git a/frontend/src/components/charts/EventDurationLineChart.tsx b/frontend/src/components/charts/EventDurationLineChart.tsx new file mode 100644 index 00000000..15768204 --- /dev/null +++ b/frontend/src/components/charts/EventDurationLineChart.tsx @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2021-2026 ahriman team. + * + * This file is part of ahriman + * (see https://github.com/arcan1s/ahriman). + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +import type { Event } from "models/Event"; +import type React from "react"; +import { Line } from "react-chartjs-2"; + +interface EventDurationLineChartProps { + events: Event[]; +} + +export default function EventDurationLineChart({ events }: EventDurationLineChartProps): React.JSX.Element { + const updateEvents = events.filter(event => event.event === "package-updated"); + const data = { + labels: updateEvents.map(event => new Date(event.created * 1000).toISOStringShort()), + datasets: [ + { + label: "update duration, s", + data: updateEvents.map(event => event.data?.took ?? 0), + cubicInterpolationMode: "monotone" as const, + tension: 0.4, + }, + ], + }; + + return ; +} diff --git a/frontend/src/components/charts/PackageCountBarChart.tsx b/frontend/src/components/charts/PackageCountBarChart.tsx new file mode 100644 index 00000000..22f542a9 --- /dev/null +++ b/frontend/src/components/charts/PackageCountBarChart.tsx @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2021-2026 ahriman team. + * + * This file is part of ahriman + * (see https://github.com/arcan1s/ahriman). + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +import { blue, indigo } from "@mui/material/colors"; +import type { RepositoryStats } from "models/RepositoryStats"; +import type React from "react"; +import { Bar } from "react-chartjs-2"; + +interface PackageCountBarChartProps { + stats: RepositoryStats; +} + +export default function PackageCountBarChart({ stats }: PackageCountBarChartProps): React.JSX.Element { + return ; +} diff --git a/frontend/src/components/charts/StatusPieChart.tsx b/frontend/src/components/charts/StatusPieChart.tsx new file mode 100644 index 00000000..6f8827c3 --- /dev/null +++ b/frontend/src/components/charts/StatusPieChart.tsx @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2021-2026 ahriman team. + * + * This file is part of ahriman + * (see https://github.com/arcan1s/ahriman). + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +import type { BuildStatus } from "models/BuildStatus.ts"; +import type { Counters } from "models/Counters"; +import type React from "react"; +import { Pie } from "react-chartjs-2"; +import { StatusColors } from "theme/StatusColors"; + +interface StatusPieChartProps { + counters: Counters; +} + +export default function StatusPieChart({ counters }: StatusPieChartProps): React.JSX.Element { + const labels = ["unknown", "pending", "building", "failed", "success"] as BuildStatus[]; + const data = { + labels: labels, + datasets: [ + { + label: "packages in status", + data: labels.map(label => counters[label]), + backgroundColor: labels.map(label => StatusColors[label]), + }, + ], + }; + + return ; +} diff --git a/frontend/src/components/common/AutoRefreshControl.tsx b/frontend/src/components/common/AutoRefreshControl.tsx new file mode 100644 index 00000000..aa872554 --- /dev/null +++ b/frontend/src/components/common/AutoRefreshControl.tsx @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2021-2026 ahriman team. + * + * This file is part of ahriman + * (see https://github.com/arcan1s/ahriman). + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +import CheckIcon from "@mui/icons-material/Check"; +import TimerIcon from "@mui/icons-material/Timer"; +import TimerOffIcon from "@mui/icons-material/TimerOff"; +import { IconButton, ListItemIcon, ListItemText, Menu, MenuItem, Tooltip } from "@mui/material"; +import type { AutoRefreshInterval } from "models/AutoRefreshInterval"; +import React, { useState } from "react"; + +interface AutoRefreshControlProps { + intervals: AutoRefreshInterval[]; + currentInterval: number; + onIntervalChange: (interval: number) => void; +} + +export default function AutoRefreshControl({ + intervals, + currentInterval, + onIntervalChange, +}: AutoRefreshControlProps): React.JSX.Element | null { + const [anchorEl, setAnchorEl] = useState(null); + + if (intervals.length === 0) { + return null; + } + + const enabled = currentInterval > 0; + + return <> + + setAnchorEl(event.currentTarget)} + color={enabled ? "primary" : "default"} + > + {enabled ? : } + + + setAnchorEl(null)} + > + { + onIntervalChange(0); + setAnchorEl(null); + }} + > + + {!enabled && } + + Off + + {intervals.map(interval => + { + onIntervalChange(interval.interval); + setAnchorEl(null); + }} + > + + {enabled && interval.interval === currentInterval && } + + {interval.text} + , + )} + + ; +} diff --git a/frontend/src/components/common/CodeBlock.tsx b/frontend/src/components/common/CodeBlock.tsx new file mode 100644 index 00000000..56917000 --- /dev/null +++ b/frontend/src/components/common/CodeBlock.tsx @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2021-2026 ahriman team. + * + * This file is part of ahriman + * (see https://github.com/arcan1s/ahriman). + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +import { Box } from "@mui/material"; +import CopyButton from "components/common/CopyButton"; +import React, { type RefObject } from "react"; + +interface CodeBlockProps { + preRef?: RefObject; + getText: () => string; + height?: number | string; + onScroll?: () => void; + wordBreak?: boolean; +} + +export default function CodeBlock({ + preRef, + getText, + height, + onScroll, + wordBreak, +}: CodeBlockProps): React.JSX.Element { + return + + + {getText()} + + + + + + ; +} diff --git a/frontend/src/components/common/CopyButton.tsx b/frontend/src/components/common/CopyButton.tsx new file mode 100644 index 00000000..2f68feb2 --- /dev/null +++ b/frontend/src/components/common/CopyButton.tsx @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2021-2026 ahriman team. + * + * This file is part of ahriman + * (see https://github.com/arcan1s/ahriman). + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +import CheckIcon from "@mui/icons-material/Check"; +import ContentCopyIcon from "@mui/icons-material/ContentCopy"; +import { IconButton, Tooltip } from "@mui/material"; +import React, { useEffect, useRef, useState } from "react"; + +interface CopyButtonProps { + getText: () => string; +} + +export default function CopyButton({ getText }: CopyButtonProps): React.JSX.Element { + const [copied, setCopied] = useState(false); + const timer = useRef>(undefined); + + useEffect(() => () => clearTimeout(timer.current), []); + + const handleCopy: () => Promise = async () => { + await navigator.clipboard.writeText(getText()); + setCopied(true); + clearTimeout(timer.current); + timer.current = setTimeout(() => setCopied(false), 2000); + }; + + return + void handleCopy()}> + {copied ? : } + + ; +} diff --git a/frontend/src/components/common/DialogHeader.tsx b/frontend/src/components/common/DialogHeader.tsx new file mode 100644 index 00000000..f4271df3 --- /dev/null +++ b/frontend/src/components/common/DialogHeader.tsx @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2021-2026 ahriman team. + * + * This file is part of ahriman + * (see https://github.com/arcan1s/ahriman). + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +import CloseIcon from "@mui/icons-material/Close"; +import { DialogTitle, IconButton, type SxProps, type Theme } from "@mui/material"; +import type React from "react"; + +interface DialogHeaderProps { + children: React.ReactNode; + onClose: () => void; + sx?: SxProps; +} + +export default function DialogHeader({ children, onClose, sx }: DialogHeaderProps): React.JSX.Element { + return + {children} + + + + ; +} diff --git a/frontend/src/components/common/RepositorySelect.tsx b/frontend/src/components/common/RepositorySelect.tsx new file mode 100644 index 00000000..b80783f2 --- /dev/null +++ b/frontend/src/components/common/RepositorySelect.tsx @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2021-2026 ahriman team. + * + * This file is part of ahriman + * (see https://github.com/arcan1s/ahriman). + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +import { FormControl, InputLabel, MenuItem, Select } from "@mui/material"; +import { useRepository } from "hooks/useRepository"; +import type { SelectedRepositoryResult } from "hooks/useSelectedRepository"; +import type React from "react"; + +export default function RepositorySelect({ + repositorySelect, +}: { repositorySelect: SelectedRepositoryResult }): React.JSX.Element { + const { repositories, current } = useRepository(); + + return + repository + + ; +} diff --git a/frontend/src/components/common/StringList.tsx b/frontend/src/components/common/StringList.tsx new file mode 100644 index 00000000..85550619 --- /dev/null +++ b/frontend/src/components/common/StringList.tsx @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2021-2026 ahriman team. + * + * This file is part of ahriman + * (see https://github.com/arcan1s/ahriman). + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +import React from "react"; + +interface StringListProps { + items: string[]; +} + +export default function StringList({ items }: StringListProps): React.JSX.Element { + return <>{items.join("\n")}; +} diff --git a/frontend/src/components/dialogs/DashboardDialog.tsx b/frontend/src/components/dialogs/DashboardDialog.tsx new file mode 100644 index 00000000..8fd42f9d --- /dev/null +++ b/frontend/src/components/dialogs/DashboardDialog.tsx @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2021-2026 ahriman team. + * + * This file is part of ahriman + * (see https://github.com/arcan1s/ahriman). + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +import { Box, Dialog, DialogContent, Grid, Typography } from "@mui/material"; +import { skipToken, useQuery } from "@tanstack/react-query"; +import PackageCountBarChart from "components/charts/PackageCountBarChart"; +import StatusPieChart from "components/charts/StatusPieChart"; +import DialogHeader from "components/common/DialogHeader"; +import { QueryKeys } from "hooks/QueryKeys"; +import { useClient } from "hooks/useClient"; +import { useRepository } from "hooks/useRepository"; +import type { InternalStatus } from "models/InternalStatus"; +import type React from "react"; +import { StatusHeaderStyles } from "theme/StatusColors"; + +interface DashboardDialogProps { + open: boolean; + onClose: () => void; +} + +export default function DashboardDialog({ open, onClose }: DashboardDialogProps): React.JSX.Element { + const client = useClient(); + const { current } = useRepository(); + + const { data: status } = useQuery({ + queryKey: current ? QueryKeys.status(current) : ["status"], + queryFn: current ? () => client.fetch.fetchServerStatus(current) : skipToken, + enabled: open, + }); + + const headerStyle = status ? StatusHeaderStyles[status.status.status] : {}; + + return + + System health + + + + {status && + <> + + + Repository name + + + {status.repository} + + + Repository architecture + + + {status.architecture} + + + + + + Current status + + + {status.status.status} + + + Updated at + + + {new Date(status.status.timestamp * 1000).toISOStringShort()} + + + + + + + + + + + + + + + + + } + + ; +} diff --git a/frontend/src/components/dialogs/KeyImportDialog.tsx b/frontend/src/components/dialogs/KeyImportDialog.tsx new file mode 100644 index 00000000..5db78803 --- /dev/null +++ b/frontend/src/components/dialogs/KeyImportDialog.tsx @@ -0,0 +1,118 @@ +/* + * Copyright (c) 2021-2026 ahriman team. + * + * This file is part of ahriman + * (see https://github.com/arcan1s/ahriman). + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +import PlayArrowIcon from "@mui/icons-material/PlayArrow"; +import RefreshIcon from "@mui/icons-material/Refresh"; +import { + Box, + Button, + Dialog, + DialogActions, + DialogContent, + TextField, +} from "@mui/material"; +import { ApiError } from "api/client/ApiError"; +import CodeBlock from "components/common/CodeBlock"; +import DialogHeader from "components/common/DialogHeader"; +import { useClient } from "hooks/useClient"; +import { useNotification } from "hooks/useNotification"; +import React, { useState } from "react"; + +interface KeyImportDialogProps { + open: boolean; + onClose: () => void; +} + +export default function KeyImportDialog({ open, onClose }: KeyImportDialogProps): React.JSX.Element { + const client = useClient(); + const { showSuccess, showError } = useNotification(); + + const [fingerprint, setFingerprint] = useState(""); + const [server, setServer] = useState("keyserver.ubuntu.com"); + const [keyBody, setKeyBody] = useState(""); + + const handleClose = (): void => { + setFingerprint(""); + setServer("keyserver.ubuntu.com"); + setKeyBody(""); + onClose(); + }; + + const handleFetch: () => Promise = async () => { + if (!fingerprint || !server) { + return; + } + try { + const result = await client.service.servicePGPFetch(fingerprint, server); + setKeyBody(result.key); + } catch (exception) { + const detail = ApiError.errorDetail(exception); + showError("Action failed", `Could not fetch key: ${detail}`); + } + }; + + const handleImport: () => Promise = async () => { + if (!fingerprint || !server) { + return; + } + try { + await client.service.servicePGPImport({ key: fingerprint, server }); + handleClose(); + showSuccess("Success", `Key ${fingerprint} has been imported`); + } catch (exception) { + const detail = ApiError.errorDetail(exception); + showError("Action failed", `Could not import key ${fingerprint} from ${server}: ${detail}`); + } + }; + + return + + Import key from PGP server + + + + setFingerprint(event.target.value)} + /> + setServer(event.target.value)} + /> + {keyBody && + + keyBody} height={300} /> + + } + + + + + + + ; +} diff --git a/frontend/src/components/dialogs/LoginDialog.tsx b/frontend/src/components/dialogs/LoginDialog.tsx new file mode 100644 index 00000000..8cf47eaa --- /dev/null +++ b/frontend/src/components/dialogs/LoginDialog.tsx @@ -0,0 +1,118 @@ +/* + * Copyright (c) 2021-2026 ahriman team. + * + * This file is part of ahriman + * (see https://github.com/arcan1s/ahriman). + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +import PersonIcon from "@mui/icons-material/Person"; +import VisibilityIcon from "@mui/icons-material/Visibility"; +import VisibilityOffIcon from "@mui/icons-material/VisibilityOff"; +import { + Button, + Dialog, + DialogActions, + DialogContent, + IconButton, + InputAdornment, + TextField, +} from "@mui/material"; +import { ApiError } from "api/client/ApiError"; +import DialogHeader from "components/common/DialogHeader"; +import { useAuth } from "hooks/useAuth"; +import { useNotification } from "hooks/useNotification"; +import React, { useState } from "react"; + +interface LoginDialogProps { + open: boolean; + onClose: () => void; +} + +export default function LoginDialog({ open, onClose }: LoginDialogProps): React.JSX.Element { + const [username, setUsername] = useState(""); + const [password, setPassword] = useState(""); + const [showPassword, setShowPassword] = useState(false); + const { login } = useAuth(); + const { showSuccess, showError } = useNotification(); + + const handleClose = (): void => { + setUsername(""); + setPassword(""); + setShowPassword(false); + onClose(); + }; + + const handleSubmit: () => Promise = async () => { + if (!username || !password) { + return; + } + try { + await login(username, password); + handleClose(); + showSuccess("Logged in", `Successfully logged in as ${username}`); + } catch (exception) { + const detail = ApiError.errorDetail(exception); + if (username === "admin" && password === "admin") { + showError("Login error", "You've entered a password for user \"root\", did you make a typo in username?"); + } else { + showError("Login error", `Could not login as ${username}: ${detail}`); + } + } + }; + + return + + Login + + + + setUsername(event.target.value)} + autoFocus + /> + setPassword(event.target.value)} + onKeyDown={event => { + if (event.key === "Enter") { + void handleSubmit(); + } + }} + slotProps={{ + input: { + endAdornment: + + setShowPassword(!showPassword)} edge="end" size="small"> + {showPassword ? : } + + , + }, + }} + /> + + + + + + ; +} diff --git a/frontend/src/components/dialogs/PackageAddDialog.tsx b/frontend/src/components/dialogs/PackageAddDialog.tsx new file mode 100644 index 00000000..4c008565 --- /dev/null +++ b/frontend/src/components/dialogs/PackageAddDialog.tsx @@ -0,0 +1,193 @@ +/* + * Copyright (c) 2021-2026 ahriman team. + * + * This file is part of ahriman + * (see https://github.com/arcan1s/ahriman). + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +import AddIcon from "@mui/icons-material/Add"; +import DeleteIcon from "@mui/icons-material/Delete"; +import PlayArrowIcon from "@mui/icons-material/PlayArrow"; +import { + Autocomplete, + Box, + Button, + Checkbox, + Dialog, + DialogActions, + DialogContent, + FormControlLabel, + IconButton, + TextField, +} from "@mui/material"; +import { useQuery } from "@tanstack/react-query"; +import { ApiError } from "api/client/ApiError"; +import DialogHeader from "components/common/DialogHeader"; +import RepositorySelect from "components/common/RepositorySelect"; +import { QueryKeys } from "hooks/QueryKeys"; +import { useClient } from "hooks/useClient"; +import { useDebounce } from "hooks/useDebounce"; +import { useNotification } from "hooks/useNotification"; +import { useSelectedRepository } from "hooks/useSelectedRepository"; +import type { AURPackage } from "models/AURPackage"; +import type { PackageActionRequest } from "models/PackageActionRequest"; +import React, { useRef, useState } from "react"; + +interface EnvironmentVariable { + id: number; + key: string; + value: string; +} + +interface PackageAddDialogProps { + open: boolean; + onClose: () => void; +} + +export default function PackageAddDialog({ open, onClose }: PackageAddDialogProps): React.JSX.Element { + const client = useClient(); + const { showSuccess, showError } = useNotification(); + const repositorySelect = useSelectedRepository(); + + const [packageName, setPackageName] = useState(""); + const [refreshDatabase, setRefreshDatabase] = useState(true); + const [environmentVariables, setEnvironmentVariables] = useState([]); + const variableIdCounter = useRef(0); + + const handleClose = (): void => { + setPackageName(""); + repositorySelect.reset(); + setRefreshDatabase(true); + setEnvironmentVariables([]); + onClose(); + }; + + const debouncedSearch = useDebounce(packageName, 500); + + const { data: searchResults = [] } = useQuery({ + queryKey: QueryKeys.search(debouncedSearch), + queryFn: () => client.service.servicePackageSearch(debouncedSearch), + enabled: debouncedSearch.length >= 3, + }); + + const handleSubmit = async (action: "add" | "request"): Promise => { + if (!packageName) { + return; + } + const repository = repositorySelect.selectedRepository; + if (!repository) { + return; + } + try { + const patches = environmentVariables.filter(variable => variable.key); + const request: PackageActionRequest = { packages: [packageName], patches }; + if (action === "add") { + request.refresh = refreshDatabase; + await client.service.servicePackageAdd(repository, request); + } else { + await client.service.servicePackageRequest(repository, request); + } + handleClose(); + showSuccess("Success", `Packages ${packageName} have been ${action === "add" ? "added" : "requested"}`); + } catch (exception) { + const detail = ApiError.errorDetail(exception); + showError("Action failed", `Package ${action} failed: ${detail}`); + } + }; + + return + + Add new packages + + + + + + pkg.package)} + inputValue={packageName} + onInputChange={(_, value) => setPackageName(value)} + renderOption={(props, option) => { + const pkg = searchResults.find(pkg => pkg.package === option); + return ( +
  • + {option}{pkg ? ` (${pkg.description})` : ""} +
  • + ); + }} + renderInput={params => + + } + /> + + setRefreshDatabase(checked)} />} + label="update pacman databases" + /> + + + + {environmentVariables.map(variable => + + { + const newKey = event.target.value; + setEnvironmentVariables(prev => + prev.map(entry => entry.id === variable.id ? { ...entry, key: newKey } : entry), + ); + }} + sx={{ flex: 1 }} + /> + = + { + const newValue = event.target.value; + setEnvironmentVariables(prev => + prev.map(entry => entry.id === variable.id ? { ...entry, value: newValue } : entry), + ); + }} + sx={{ flex: 1 }} + /> + setEnvironmentVariables(prev => prev.filter(entry => entry.id !== variable.id))}> + + + , + )} +
    + + + + + +
    ; +} diff --git a/frontend/src/components/dialogs/PackageInfoDialog.tsx b/frontend/src/components/dialogs/PackageInfoDialog.tsx new file mode 100644 index 00000000..efc56145 --- /dev/null +++ b/frontend/src/components/dialogs/PackageInfoDialog.tsx @@ -0,0 +1,194 @@ +/* + * Copyright (c) 2021-2026 ahriman team. + * + * This file is part of ahriman + * (see https://github.com/arcan1s/ahriman). + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +import { Box, Dialog, DialogContent, Tab, Tabs } from "@mui/material"; +import { skipToken, useQuery, useQueryClient } from "@tanstack/react-query"; +import { ApiError } from "api/client/ApiError"; +import DialogHeader from "components/common/DialogHeader"; +import BuildLogsTab from "components/package/BuildLogsTab"; +import ChangesTab from "components/package/ChangesTab"; +import EventsTab from "components/package/EventsTab"; +import PackageDetailsGrid from "components/package/PackageDetailsGrid"; +import PackageInfoActions from "components/package/PackageInfoActions"; +import PackagePatchesList from "components/package/PackagePatchesList"; +import { QueryKeys } from "hooks/QueryKeys"; +import { useAuth } from "hooks/useAuth"; +import { useAutoRefresh } from "hooks/useAutoRefresh"; +import { useClient } from "hooks/useClient"; +import { useNotification } from "hooks/useNotification"; +import { useRepository } from "hooks/useRepository"; +import type { AutoRefreshInterval } from "models/AutoRefreshInterval"; +import type { Dependencies } from "models/Dependencies"; +import type { PackageStatus } from "models/PackageStatus"; +import type { Patch } from "models/Patch"; +import React, { useState } from "react"; +import { StatusHeaderStyles } from "theme/StatusColors"; +import { defaultInterval } from "utils"; + +interface PackageInfoDialogProps { + packageBase: string | null; + open: boolean; + onClose: () => void; + autoRefreshIntervals: AutoRefreshInterval[]; +} + +export default function PackageInfoDialog({ + packageBase, + open, + onClose, + autoRefreshIntervals, +}: PackageInfoDialogProps): React.JSX.Element { + const client = useClient(); + const { current } = useRepository(); + const { isAuthorized } = useAuth(); + const { showSuccess, showError } = useNotification(); + const queryClient = useQueryClient(); + + const [localPackageBase, setLocalPackageBase] = useState(packageBase); + if (packageBase !== null && packageBase !== localPackageBase) { + setLocalPackageBase(packageBase); + } + + const [tabIndex, setTabIndex] = useState(0); + const [refreshDatabase, setRefreshDatabase] = useState(true); + + const handleClose = (): void => { + setTabIndex(0); + setRefreshDatabase(true); + onClose(); + }; + + const autoRefresh = useAutoRefresh("package-info-autoreload-button", defaultInterval(autoRefreshIntervals)); + + const { data: packageData } = useQuery({ + queryKey: localPackageBase && current ? QueryKeys.package(localPackageBase, current) : ["packages"], + queryFn: localPackageBase && current ? () => client.fetch.fetchPackage(localPackageBase, current) : skipToken, + enabled: open, + refetchInterval: autoRefresh.interval > 0 ? autoRefresh.interval : false, + }); + + const { data: dependencies } = useQuery({ + queryKey: localPackageBase && current ? QueryKeys.dependencies(localPackageBase, current) : ["dependencies"], + queryFn: localPackageBase && current + ? () => client.fetch.fetchPackageDependencies(localPackageBase, current) : skipToken, + enabled: open, + }); + + const { data: patches = [] } = useQuery({ + queryKey: localPackageBase ? QueryKeys.patches(localPackageBase) : ["patches"], + queryFn: localPackageBase ? () => client.fetch.fetchPackagePatches(localPackageBase) : skipToken, + enabled: open, + }); + + const description: PackageStatus | undefined = packageData?.[0]; + const pkg = description?.package; + const status = description?.status; + const headerStyle = status ? StatusHeaderStyles[status.status] : {}; + + const handleUpdate: () => Promise = async () => { + if (!localPackageBase || !current) { + return; + } + try { + await client.service.servicePackageAdd(current, { packages: [localPackageBase], refresh: refreshDatabase }); + showSuccess("Success", `Run update for packages ${localPackageBase}`); + } catch (exception) { + showError("Action failed", `Package update failed: ${ApiError.errorDetail(exception)}`); + } + }; + + const handleRemove: () => Promise = async () => { + if (!localPackageBase || !current) { + return; + } + try { + await client.service.servicePackageRemove(current, [localPackageBase]); + showSuccess("Success", `Packages ${localPackageBase} have been removed`); + onClose(); + } catch (exception) { + showError("Action failed", `Could not remove package: ${ApiError.errorDetail(exception)}`); + } + }; + + const handleDeletePatch: (key: string) => Promise = async key => { + if (!localPackageBase) { + return; + } + try { + await client.service.servicePackagePatchRemove(localPackageBase, key); + void queryClient.invalidateQueries({ queryKey: QueryKeys.patches(localPackageBase) }); + } catch (exception) { + showError("Action failed", `Could not delete variable: ${ApiError.errorDetail(exception)}`); + } + }; + + return + + {pkg && status + ? `${pkg.base} ${status.status} at ${new Date(status.timestamp * 1000).toISOStringShort()}` + : localPackageBase ?? ""} + + + + {pkg && + <> + + void handleDeletePatch(key)} + /> + + + setTabIndex(index)}> + + + + + + + {tabIndex === 0 && localPackageBase && current && + + } + {tabIndex === 1 && localPackageBase && current && + + } + {tabIndex === 2 && localPackageBase && current && + + } + + } + + + void handleUpdate()} + onRemove={() => void handleRemove()} + autoRefreshIntervals={autoRefreshIntervals} + autoRefreshInterval={autoRefresh.interval} + onAutoRefreshIntervalChange={autoRefresh.setInterval} + /> + ; +} diff --git a/frontend/src/components/dialogs/PackageRebuildDialog.tsx b/frontend/src/components/dialogs/PackageRebuildDialog.tsx new file mode 100644 index 00000000..f7863d29 --- /dev/null +++ b/frontend/src/components/dialogs/PackageRebuildDialog.tsx @@ -0,0 +1,88 @@ +/* + * Copyright (c) 2021-2026 ahriman team. + * + * This file is part of ahriman + * (see https://github.com/arcan1s/ahriman). + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +import PlayArrowIcon from "@mui/icons-material/PlayArrow"; +import { Button, Dialog, DialogActions, DialogContent, TextField } from "@mui/material"; +import { ApiError } from "api/client/ApiError"; +import DialogHeader from "components/common/DialogHeader"; +import RepositorySelect from "components/common/RepositorySelect"; +import { useClient } from "hooks/useClient"; +import { useNotification } from "hooks/useNotification"; +import { useSelectedRepository } from "hooks/useSelectedRepository"; +import React, { useState } from "react"; + +interface PackageRebuildDialogProps { + open: boolean; + onClose: () => void; +} + +export default function PackageRebuildDialog({ open, onClose }: PackageRebuildDialogProps): React.JSX.Element { + const client = useClient(); + const { showSuccess, showError } = useNotification(); + const repositorySelect = useSelectedRepository(); + + const [dependency, setDependency] = useState(""); + + const handleClose = (): void => { + setDependency(""); + repositorySelect.reset(); + onClose(); + }; + + const handleRebuild: () => Promise = async () => { + if (!dependency) { + return; + } + const repository = repositorySelect.selectedRepository; + if (!repository) { + return; + } + try { + await client.service.serviceRebuild(repository, [dependency]); + handleClose(); + showSuccess("Success", `Repository rebuild has been run for packages which depend on ${dependency}`); + } catch (exception) { + const detail = ApiError.errorDetail(exception); + showError("Action failed", `Repository rebuild failed: ${detail}`); + } + }; + + return + + Rebuild depending packages + + + + + + setDependency(event.target.value)} + /> + + + + + + ; +} diff --git a/frontend/src/components/layout/AppLayout.tsx b/frontend/src/components/layout/AppLayout.tsx new file mode 100644 index 00000000..0b53caa5 --- /dev/null +++ b/frontend/src/components/layout/AppLayout.tsx @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2021-2026 ahriman team. + * + * This file is part of ahriman + * (see https://github.com/arcan1s/ahriman). + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +import { Box, Container } from "@mui/material"; +import { useQuery } from "@tanstack/react-query"; +import LoginDialog from "components/dialogs/LoginDialog"; +import Footer from "components/layout/Footer"; +import Navbar from "components/layout/Navbar"; +import PackageTable from "components/table/PackageTable"; +import { QueryKeys } from "hooks/QueryKeys"; +import { useAuth } from "hooks/useAuth"; +import { useClient } from "hooks/useClient"; +import { useRepository } from "hooks/useRepository"; +import type { InfoResponse } from "models/InfoResponse"; +import React, { useEffect, useState } from "react"; + +export default function AppLayout(): React.JSX.Element { + const client = useClient(); + const { setAuthState } = useAuth(); + const { setRepositories } = useRepository(); + const [loginOpen, setLoginOpen] = useState(false); + + const { data: info } = useQuery({ + queryKey: QueryKeys.info, + queryFn: () => client.fetch.fetchServerInfo(), + staleTime: Infinity, + }); + + // Sync info to contexts when loaded + useEffect(() => { + if (info) { + setAuthState({ enabled: info.auth.enabled, username: info.auth.username ?? null }); + setRepositories(info.repositories); + } + }, [info, setAuthState, setRepositories]); + + return + + + + + + + + + + + +