diff --git a/.dockerignore b/.dockerignore index c843ac6..dbeb426 100644 --- a/.dockerignore +++ b/.dockerignore @@ -14,7 +14,5 @@ secrets .gitignore LICENSE README.md -install-util.sh -install.sh CHANGELOG -docker-compose.yml.example +docker-compose.example.yml diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml new file mode 100644 index 0000000..79f75b9 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -0,0 +1,59 @@ +name: Bug report +description: Create a report to help us improve +title: "[BUG]: " +labels: ['Type: Bug', 'Status: Needs Triage'] +body: + - type: checkboxes + attributes: + label: Is there an existing issue for this? + description: Please search to see if an open or closed issue already exists for the feature you are requesting. If a request exists and is closed note that it may only be fixed in an unstable branch. + options: + - label: I have searched the existing open and closed issues + required: true + - type: textarea + attributes: + label: Describe the bug + description: A clear and concise description of what the bug is. + validations: + required: true + - type: textarea + attributes: + label: To Reproduce + description: | + Steps to reproduce the behavior: + 1. Go to '...' + 2. Click on '....' + 3. Scroll down to '....' + 4. See error + validations: + required: true + - type: textarea + attributes: + label: Expected behavior + description: A clear and concise description of what you expected to happen. + validations: + required: true + - type: textarea + attributes: + label: Screenshots + description: If applicable, add screenshots to help explain your problem. + validations: + required: false + - type: input + attributes: + label: OS + description: e.g. Linux + validations: + required: false + - type: input + attributes: + label: Version + description: e.g. 22 + validations: + required: false + - type: textarea + attributes: + label: Additional context + description: Add any other context about the problem here. + validations: + required: false diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000..3ba13e0 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1 @@ +blank_issues_enabled: false diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml new file mode 100644 index 0000000..7e6c25b --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -0,0 +1,39 @@ +name: Feature Request +description: Suggest an idea for this project +title: "[FEAT]: " +labels: ['Type: Feature', 'Status: Needs Triage'] +body: +- type: checkboxes + attributes: + label: Is there an existing issue for this? + description: Please search to see if an open or closed issue already exists for the feature you are requesting. If a request exists and is closed note that it may only be fixed in an unstable branch. + options: + - label: I have searched the existing open and closed issues + required: true +- type: textarea + attributes: + label: Is your feature request related to a problem? Please describe + description: A clear and concise description of what the problem is. + validations: + required: true +- type: textarea + attributes: + label: Describe the solution you'd like + description: A clear and concise description of what you want to happen. + validations: + required: true +- type: textarea + attributes: + label: Describe alternatives you've considered + description: A clear and concise description of any alternative solutions or features you've considered. + validations: + required: true +- type: textarea + attributes: + label: Anything else? + description: | + Links? References? Mockups? Anything that will give us more context about the feature you are encountering! + + Tip: You can attach images or log files by clicking this area to highlight it and then dragging files in. + validations: + required: true diff --git a/.github/workflows/integration-dev.yml b/.github/workflows/integration-dev.yml new file mode 100644 index 0000000..80c6dd4 --- /dev/null +++ b/.github/workflows/integration-dev.yml @@ -0,0 +1,17 @@ +name: Integration Test Dev Branch with Server + +on: + push: + branches: + - dev + pull_request: + +jobs: + integration-test: + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - uses: MediaGarrd/MediaGarrd-Stack-Testing@main + with: + server-branch: dev + client-branch: ${{ github.head_ref || github.ref_name }} diff --git a/.github/workflows/integration-main.yml b/.github/workflows/integration-main.yml new file mode 100644 index 0000000..bd5d151 --- /dev/null +++ b/.github/workflows/integration-main.yml @@ -0,0 +1,16 @@ +name: Integration Test Main Branch with Server + +on: + push: + branches: + - main + +jobs: + integration-test: + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - uses: MediaGarrd/MediaGarrd-Stack-Testing@main + with: + server-branch: main + client-branch: main diff --git a/.github/workflows/issue_handling.yml b/.github/workflows/issue_handling.yml new file mode 100644 index 0000000..a9f75ca --- /dev/null +++ b/.github/workflows/issue_handling.yml @@ -0,0 +1,55 @@ +name: Handle duplicate status label + +on: + issues: + types: [labeled, unlabeled] + +jobs: + correct-status-labels: + runs-on: ubuntu-latest + steps: + - name: Ensure one Status label per issue + uses: actions/github-script@v7 + with: + github-token: ${{ secrets.MEDIAGARRD_CLIENT_ACTIONS_TOKEN }} + script: | + const issueNumber = context.payload.issue.number; + const statusLabelsToCheck = [ + "Status: Needs Triage", + "Status: Approved", + "Status: Waiting on Child Issues", + "Status: Waiting on Server Update" + ]; + + const existingLabels = context.payload.issue.labels.map(label => label.name); + const existingStatusLabels = existingLabels.filter(label => statusLabelsToCheck.includes(label)); + const addedLabel = context.payload.action === "labeled" ? context.payload.label.name : null; + + let keep = null; + if (statusLabelsToCheck.includes(addedLabel)) { + keep = addedLabel; + } else if (existingStatusLabels.length == 1) { + keep = existingStatusLabels[0]; + } + + for (const label of existingStatusLabels.filter(label => label !== keep)) { + await github.rest.issues.removeLabel({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: issueNumber, + name: label + }); + console.log(`Removed label "${label}" from issue #${issueNumber}`); + } + + if (keep) { + console.log(`Status label: "${keep}" is set correctly`); + } else { + await github.rest.issues.addLabels({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: issueNumber, + labels: ["Status: Needs Triage"] + }); + } + diff --git a/.github/workflows/pr_handling.yml b/.github/workflows/pr_handling.yml new file mode 100644 index 0000000..fe9016a --- /dev/null +++ b/.github/workflows/pr_handling.yml @@ -0,0 +1,46 @@ +name: Require approved issue + +on: + pull_request: + types: [opened, edited, reopened, synchronize] + +jobs: + require-approved-issue: + if: github.head_ref != 'dev' + runs-on: ubuntu-latest + permissions: + issues: read + pull-requests: read + steps: + - name: Ensure every linked issue is approved + uses: actions/github-script@v7 + with: + script: | + const { repository } = await github.graphql(` + query($owner: String!, $repo: String!, $number: Int!) { + repository(owner: $owner, name: $repo) { + pullRequest(number: $number) { + closingIssuesReferences(first: 25) { + nodes { number labels(first: 25) { nodes { name } } } + } + } + } + }`, { + owner: context.repo.owner, + repo: context.repo.repo, + number: context.payload.pull_request.number + }); + + const issues = repository.pullRequest.closingIssuesReferences.nodes; + if (issues.length === 0) { + core.setFailed("Link the approved issue this pull request resolves, e.g. \"Closes #12\" in the description"); + return; + } + + const unapproved = issues.filter(issue => !issue.labels.nodes.some(label => label.name === "Status: Approved")); + if (unapproved.length > 0) { + core.setFailed(`Linked issues without "Status: Approved": ${unapproved.map(issue => `#${issue.number}`).join(", ")}`); + return; + } + + console.log(`All linked issues are approved: ${issues.map(issue => `#${issue.number}`).join(", ")}`); diff --git a/.gitignore b/.gitignore index 6703b86..6feddf8 100644 --- a/.gitignore +++ b/.gitignore @@ -2,7 +2,6 @@ .gradle .settings/ build -gradle/ **/.settings/ **/.project **/.classpath diff --git a/CHANGELOG b/CHANGELOG index e69de29..d586cdb 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -0,0 +1,26 @@ +# CHANGELOG + +## 10-26-26 +- Finished renaming the codebase to MediaGarrd +- Added issue templates, issue label and pull request workflows, and integration test workflows +- Added a `Makefile` with a `test` target +- Removed `install.sh`: `docker-compose.example.yml` now works as-is, the container keeps its downloads and state on the mounted volumes by default, and everything else is set from the web page +- `MEDIAGARRD_SERVER_PORT` now defaults to `38471` to match the server, and `MEDIAGARRD_SERVER_IP` is optional and accepts `:` +- The client connects to `MEDIAGARRD_SERVER_IP` on its own at startup and keeps trying every 30 seconds until a server is selected, so scheduled pickups work without opening the web page +- Added a Server Config view, opened from the toggle in the top bar, that changes the connected server's backup location, interval, and retention count and adds, edits, and removes its services +- Split the web page into an HTML page, a stylesheet, and JavaScript modules +- Every API endpoint now returns errors as `{"error": "..."}`, passing on the server's own message and status code when the server rejects a request +- Fixed the server schedule being sent as a number of seconds instead of an ISO-8601 duration +- The Gradle wrapper is now committed so the project builds without a local Gradle install +- Network discovery finishes in a couple of seconds instead of minutes: it checks for an open port before making an HTTP request, probes many hosts at once, skips Docker and VPN interfaces, and only counts servers that answer with a MediaGarrd health response +- Connecting by IP accepts `host:port`, stops right away when the host is unreachable, and scans every port of a reachable host in about a second +- Fixed the connection badge being overwritten by the periodic health check while a scan or connection attempt is running +- The badge and status panel show when the selected server is not responding, the backup list says why it could not be loaded, and everything reloads on its own when the server comes back +- The backup list reloads when a backup run started elsewhere finishes, and the Dashboard shows saved server settings as soon as you switch back to it +- "Scan Local Network" reports how many servers the scan actually found +- Requests to the server now time out instead of hanging when it is unreachable, and health checks pause while the page is hidden +- Starting a download of a backup that is already downloading reuses the running download instead of writing the same file twice +- Unknown backups and download tasks return 404, invalid pickup intervals and server URLs return 400, and finished download tasks are forgotten after 10 minutes +- Backup file names from the server can no longer write outside the download directory +- The client state file is written atomically so a crash cannot leave it half written +- Removed unused code and dependencies diff --git a/Dockerfile b/Dockerfile index b6aca51..3be39cf 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,7 +1,7 @@ FROM gradle:9.4.0-jdk21 AS build WORKDIR /workspace COPY . . -RUN gradle :bootJar --no-daemon +RUN --mount=type=cache,target=/home/gradle/.gradle gradle :bootJar --no-daemon --stacktrace --info --warning-mode all FROM eclipse-temurin:21-jre WORKDIR /app diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..9fee8ce --- /dev/null +++ b/Makefile @@ -0,0 +1,5 @@ +.PHONY: test + +test: + ./gradlew test --warning-mode all + diff --git a/README.md b/README.md index 0101992..35e5bed 100644 --- a/README.md +++ b/README.md @@ -2,13 +2,46 @@ This is the official client for [MediaGarrd](https://github.com/MediaGarrd/MediaGarrd). +## Requirements +- Docker with Compose v2 (`docker compose ...`) +- A running [MediaGarrd Server](https://github.com/MediaGarrd/Server) that has finished its first-time setup + ## Installation ```bash git clone --depth 1 https://github.com/MediaGarrd/Client.git cd Client -./install.sh # Drops .env, client.env, and docker-compose.yml +cp docker-compose.example.yml docker-compose.yml +docker compose up --build -d +``` + +Then open `http://:8081`. + +The defaults in `docker-compose.yml` work as-is. To change them before the first start: +- **Port:** change both `CLIENT_PORT` and the `ports` mapping (default `8081`). +- **Where downloaded backups are stored on the host:** change the left side of the `./data/client/downloads` volume. +- **Where the client keeps its state on the host:** change the left side of the `./data/client/state` volume. This holds the selected server, known servers, and pickup interval, so keep it on persistent storage. +- **Server port to look for:** `MEDIAGARRD_SERVER_PORT` (default `38471`, the server's default). Discovery and "Connect by IP" try this port first. +- **Connect to a server automatically:** add `MEDIAGARRD_SERVER_IP=` (or `:`) to `environment`. Until a server is selected, the client connects to this address as soon as it answers. Without it, pick a server in the web page. + +`CLIENT_PICKUP_INTERVAL` (ISO-8601, default `PT12H`) only sets the initial value. Once the interval has been saved in the web page, the stored value is used. + +## Usage +- **Dashboard** connects to a MediaGarrd server by IP, from the list of known servers, or by scanning the local network. It shows the server's status, runs a backup, downloads backups, and sets how often the client downloads the latest backup on its own. +- **Server Config** changes the connected server's backup location, backup interval, and number of backups to keep, and adds, edits, and removes the services it backs up. The server must have finished its first-time setup (the `/config` page on the server) before it accepts changes from the client. + +Every setting is stored in the `./data/client/state` volume and survives restarts and container rebuilds. + +### Finding servers +"Scan Local Network" checks every address of the networks the client is attached to, on `MEDIAGARRD_SERVER_PORT`, `38471`, `8080`, and `80`, and lists every MediaGarrd server that answers. "Connect by IP" also accepts `:`, and scans every port of the host when the server is not on one of those ports. + +With the default Docker networking the client only sees the container network, so a scan finds servers running on the same host but not on other machines. Use "Connect by IP" or `MEDIAGARRD_SERVER_IP` for those, or add `network_mode: host` to the service (and remove its `ports` mapping) so the scan covers your LAN. + +## Updating +```bash +git pull docker compose up --build -d ``` +Downloaded backups and the client state live in the mounted `./data/client` volumes and are kept. ## License [GPLv3](./LICENSE) diff --git a/build.gradle.kts b/build.gradle.kts index 60673ae..1c249cd 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -5,7 +5,6 @@ plugins { } repositories { - // Use Maven Central for resolving dependencies. mavenCentral() } diff --git a/docker-compose.example.yml b/docker-compose.example.yml index 9ad9bfb..4c12fe2 100644 --- a/docker-compose.example.yml +++ b/docker-compose.example.yml @@ -2,18 +2,15 @@ services: mediagarrd-client: build: context: . - dockerfile: ./Dockerfile + dockerfile: Dockerfile container_name: mediagarrd-client environment: - CLIENT_PORT=8081 - - CLIENT_PICKUP_INTERVAL=PT1H - - CLIENT_DOWNLOAD_DIRECTORY=/var/lib/mediagarrd/downloads - - CLIENT_STATE_FILE=/var/lib/mediagarrd/client/state.json + - CLIENT_PICKUP_INTERVAL=PT12H - MEDIAGARRD_SERVER_PORT=38471 - - MEDIAGARRD_SERVER_IP=192.168.50.55 ports: - "8081:8081" volumes: - "./data/client/downloads:/var/lib/mediagarrd/downloads" - - "./data/client:/var/lib/mediagarrd/client" + - "./data/client/state:/var/lib/mediagarrd/client" restart: unless-stopped diff --git a/gradle.properties b/gradle.properties index 377538c..1385fa5 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,5 +1,2 @@ -# This file was generated by the Gradle 'init' task. -# https://docs.gradle.org/current/userguide/build_environment.html#sec:gradle_configuration_properties - org.gradle.configuration-cache=true diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..d997cfc Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..dbc3ce4 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.4.0-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew.bat b/gradlew.bat index c4bdd3a..e509b2d 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -1,93 +1,93 @@ -@rem -@rem Copyright 2015 the original author or authors. -@rem -@rem Licensed under the Apache License, Version 2.0 (the "License"); -@rem you may not use this file except in compliance with the License. -@rem You may obtain a copy of the License at -@rem -@rem https://www.apache.org/licenses/LICENSE-2.0 -@rem -@rem Unless required by applicable law or agreed to in writing, software -@rem distributed under the License is distributed on an "AS IS" BASIS, -@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -@rem See the License for the specific language governing permissions and -@rem limitations under the License. -@rem -@rem SPDX-License-Identifier: Apache-2.0 -@rem - -@if "%DEBUG%"=="" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -set DIRNAME=%~dp0 -if "%DIRNAME%"=="" set DIRNAME=. -@rem This is normally unused -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Resolve any "." and ".." in APP_HOME to make it shorter. -for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if %ERRORLEVEL% equ 0 goto execute - -echo. 1>&2 -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 -echo. 1>&2 -echo Please set the JAVA_HOME variable in your environment to match the 1>&2 -echo location of your Java installation. 1>&2 - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto execute - -echo. 1>&2 -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 -echo. 1>&2 -echo Please set the JAVA_HOME variable in your environment to match the 1>&2 -echo location of your Java installation. 1>&2 - -goto fail - -:execute -@rem Setup the command line - - - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* - -:end -@rem End local scope for the variables with windows NT shell -if %ERRORLEVEL% equ 0 goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -set EXIT_CODE=%ERRORLEVEL% -if %EXIT_CODE% equ 0 set EXIT_CODE=1 -if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% -exit /b %EXIT_CODE% - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/install-util.sh b/install-util.sh deleted file mode 100644 index 6868df0..0000000 --- a/install-util.sh +++ /dev/null @@ -1,40 +0,0 @@ -#!/usr/bin/env bash - -ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -SECRETS_DIR="$ROOT_DIR/secrets" -COMPOSE_FILE="$ROOT_DIR/docker-compose.yml" -ENV_FILE="$ROOT_DIR/.env" -SERVER_ENV_FILE="$SECRETS_DIR/server.env" -CLIENT_ENV_FILE="$SECRETS_DIR/client.env" - -mkdir -p "$SECRETS_DIR" - -prompt() { - local var_name="$1" - local prompt_text="$2" - local default_value="${3:-}" - local value="" - - read -r -p "$prompt_text" value - if [[ -z "$value" ]]; then - value="$default_value" - fi - - printf -v "$var_name" '%s' "$value" -} - -yes_no() { - local var_name="$1" - local prompt_text="$2" - local default_value="${3:-y}" - local response - - read -r -p "$prompt_text" response - response="${response:-$default_value}" - if [[ "$response" =~ ^[Yy]([Ee][Ss])?$ ]]; then - printf -v "$var_name" 'true' - else - printf -v "$var_name" 'false' - fi -} - diff --git a/install.sh b/install.sh deleted file mode 100644 index 1ac6736..0000000 --- a/install.sh +++ /dev/null @@ -1,57 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail -source ./install-util.sh - -prompt client_port "MediaGarrd-Client host port [8081]: " "8081" -prompt pickup_interval "Client automatic pickup interval in ISO-8601 format [PT12H]: " "PT12H" -prompt server_ip "MediaGarrd-Server IP [192.168.1.10]: " "192.168.1.10" -prompt client_downloads_host "Client download host path [./data/client/downloads]: " "./data/client/downloads" -prompt client_state_host "Client state host path [./data/client]: " "./data/client" - -cat > "$ENV_FILE" < "$CLIENT_ENV_FILE" < "$COMPOSE_FILE" <> serverRejected(RestClientResponseException e) { + String message = null; + try { + ServerError body = e.getResponseBodyAs(ServerError.class); + message = body == null ? null : body.error(); + } catch (RuntimeException ignored) { + } + String reason = message == null ? "MediaGarrd server responded with " + e.getStatusCode().value() : message; + LOGGER.warn("MediaGarrd server rejected request: {}", reason); + return error(e.getStatusCode(), reason); + } + + @ExceptionHandler(ResourceAccessException.class) + public ResponseEntity> serverUnreachable(ResourceAccessException e) { + LOGGER.warn("MediaGarrd server unreachable: {}", e.getMessage()); + return e.getCause() instanceof HttpTimeoutException || e.getCause() instanceof SocketTimeoutException + ? error(HttpStatus.GATEWAY_TIMEOUT, "MediaGarrd server did not respond in time") + : error(HttpStatus.BAD_GATEWAY, "MediaGarrd server is unreachable"); + } + + @ExceptionHandler(ResponseStatusException.class) + public ResponseEntity> rejected(ResponseStatusException e) { + LOGGER.warn("Rejected request: {}", e.getReason()); + return error(e.getStatusCode(), e.getReason()); + } + + @ExceptionHandler(HttpMessageNotReadableException.class) + public ResponseEntity> unreadable(HttpMessageNotReadableException e) { + LOGGER.warn("Unreadable request body: {}", e.getMessage()); + return error(HttpStatus.BAD_REQUEST, "Request body is missing or malformed"); + } + + @ExceptionHandler({IllegalArgumentException.class, IllegalStateException.class}) + public ResponseEntity> failed(RuntimeException e) { + HttpStatus status = e instanceof IllegalArgumentException ? HttpStatus.BAD_REQUEST : HttpStatus.INTERNAL_SERVER_ERROR; + if (status.is5xxServerError()) { + LOGGER.error("Request failed: {}", e.getMessage()); + } else { + LOGGER.warn("Rejected request: {}", e.getMessage()); + } + return error(status, e.getMessage()); + } + + private static ResponseEntity> error(HttpStatusCode status, String message) { + String fallback = status instanceof HttpStatus known ? known.getReasonPhrase() : "Request failed"; + return ResponseEntity.status(status).body(Map.of("error", Objects.requireNonNullElse(message, fallback))); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/api/ClientController.java b/src/main/java/wellatleastitried/mediagarrdclient/api/ClientController.java new file mode 100644 index 0000000..87ea9ae --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/api/ClientController.java @@ -0,0 +1,147 @@ +package wellatleastitried.mediagarrdclient.api; + +import java.net.URI; +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import wellatleastitried.mediagarrdclient.dto.BackupDto; +import wellatleastitried.mediagarrdclient.dto.ClientStatusDto; +import wellatleastitried.mediagarrdclient.dto.ConnectionStatusDto; +import wellatleastitried.mediagarrdclient.dto.IntervalUpdateRequest; +import wellatleastitried.mediagarrdclient.dto.PickupProgressDto; +import wellatleastitried.mediagarrdclient.dto.PickupStartDto; +import wellatleastitried.mediagarrdclient.dto.ServerSelectionRequest; +import wellatleastitried.mediagarrdclient.service.BackupPickupService; +import wellatleastitried.mediagarrdclient.service.ClientStateService; +import wellatleastitried.mediagarrdclient.service.ServerApiService; +import wellatleastitried.mediagarrdclient.service.ServerDiscoveryService; + +@RestController +@RequestMapping("/api/client") +public class ClientController { + + private static final Logger LOGGER = LoggerFactory.getLogger(ClientController.class); + + private final ClientStateService stateService; + private final ServerDiscoveryService discoveryService; + private final ServerApiService serverApiService; + private final BackupPickupService pickupService; + + public ClientController( + ClientStateService stateService, + ServerDiscoveryService discoveryService, + ServerApiService serverApiService, + BackupPickupService pickupService + ) { + this.stateService = stateService; + this.discoveryService = discoveryService; + this.serverApiService = serverApiService; + this.pickupService = pickupService; + } + + @GetMapping("/status") + public ClientStatusDto status() { + discoveryService.connectPreferredServer(); + return currentStatus(); + } + + @PostMapping("/discover") + public List discover() { + List discovered = discoveryService.discover(); + stateService.updateKnownServers(discovered); + return discovered; + } + + @GetMapping("/server-health") + public ConnectionStatusDto serverHealth() { + String activeServer = stateService.getActiveServer(); + if (isBlank(activeServer)) { + return new ConnectionStatusDto("", false); + } + try { + return new ConnectionStatusDto(activeServer, true, serverApiService.health(activeServer)); + } catch (RuntimeException e) { + LOGGER.debug("{} is unreachable: {}", activeServer, e.getMessage()); + return new ConnectionStatusDto(activeServer, false); + } + } + + @PutMapping("/server") + public ClientStatusDto setServer(@RequestBody ServerSelectionRequest request) { + if (!isBlank(request.serverUrl())) { + stateService.setActiveServer(normalizeServerUrl(request.serverUrl())); + return currentStatus(); + } + if (isBlank(request.serverIp())) { + throw new IllegalArgumentException("Either serverUrl or serverIp must be provided"); + } + Integer port = request.serverPort(); + if (port != null && (port < 1 || port > 65535)) { + throw new IllegalArgumentException("serverPort must be between 1 and 65535"); + } + String resolved = discoveryService.resolveServerByIp(request.serverIp(), port) + .orElseThrow(() -> new IllegalArgumentException("No MediaGarrd server found at " + request.serverIp().trim())); + stateService.setActiveServer(resolved); + return currentStatus(); + } + + @GetMapping("/backups") + public List listBackups() { + return serverApiService.listBackups(stateService.requireActiveServer()); + } + + @PostMapping("/backups/run") + public void runBackup() { + serverApiService.triggerBackup(stateService.requireActiveServer()); + } + + @PostMapping("/pickup") + public PickupStartDto pickupLatest() { + return pickupService.startPickupLatestTask(); + } + + @PostMapping("/pickup/{id}") + public PickupStartDto pickupById(@PathVariable String id) { + return pickupService.startPickupByIdTask(id); + } + + @GetMapping("/pickup/progress/{taskId}") + public PickupProgressDto pickupProgress(@PathVariable String taskId) { + return pickupService.pickupProgress(taskId); + } + + @PutMapping("/pickup-interval") + public ClientStatusDto updatePickupInterval(@RequestBody IntervalUpdateRequest request) { + pickupService.updatePickupInterval(request.interval()); + return currentStatus(); + } + + private ClientStatusDto currentStatus() { + return new ClientStatusDto(stateService.getActiveServer(), stateService.getPickupInterval(), stateService.getKnownServers()); + } + + static String normalizeServerUrl(String serverUrl) { + String trimmed = serverUrl.trim().replaceAll("/+$", ""); + try { + URI uri = URI.create(trimmed); + if (("http".equals(uri.getScheme()) || "https".equals(uri.getScheme())) && !isBlank(uri.getHost())) { + return trimmed; + } + } catch (IllegalArgumentException ignored) { + } + throw new IllegalArgumentException("serverUrl must be an http:// or https:// URL: " + serverUrl); + } + + private static boolean isBlank(String value) { + return value == null || value.isBlank(); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/api/Endpoints.java b/src/main/java/wellatleastitried/mediagarrdclient/api/Endpoints.java new file mode 100644 index 0000000..6b83040 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/api/Endpoints.java @@ -0,0 +1,21 @@ +package wellatleastitried.mediagarrdclient.api; + +public enum Endpoints { + + SERVER_HEALTH("/api/v1/health"), + SERVER_BACKUPS("/api/v1/backups"), + SERVER_BACKUP_RUN("/api/v1/backups/run"), + SERVER_SCHEDULE("/api/v1/schedule"), + SERVER_CONFIG("/api/v1/config"), + SERVER_SERVICES("/api/v1/services"); + + private final String path; + + Endpoints(String path) { + this.path = path; + } + + public String getPath() { + return path; + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/api/ServerConfigController.java b/src/main/java/wellatleastitried/mediagarrdclient/api/ServerConfigController.java new file mode 100644 index 0000000..642ca4d --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/api/ServerConfigController.java @@ -0,0 +1,86 @@ +package wellatleastitried.mediagarrdclient.api; + +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestController; + +import wellatleastitried.mediagarrdclient.dto.ServerConfigDto; +import wellatleastitried.mediagarrdclient.dto.ServerStatusDto; +import wellatleastitried.mediagarrdclient.dto.ServiceDto; +import wellatleastitried.mediagarrdclient.service.ClientStateService; +import wellatleastitried.mediagarrdclient.service.ServerApiService; + +@RestController +@RequestMapping("/api/client") +public class ServerConfigController { + + private static final Logger LOGGER = LoggerFactory.getLogger(ServerConfigController.class); + + private final ClientStateService stateService; + private final ServerApiService serverApiService; + + public ServerConfigController(ClientStateService stateService, ServerApiService serverApiService) { + this.stateService = stateService; + this.serverApiService = serverApiService; + } + + @GetMapping("/server-config") + public ServerConfigDto serverConfig() { + String activeServer = stateService.requireActiveServer(); + LOGGER.info("GET /api/client/server-config, forwarding to {}", activeServer); + return serverApiService.serverConfig(activeServer); + } + + @PutMapping("/server-config") + public ServerConfigDto updateServerConfig(@RequestBody ServerConfigDto request) { + String activeServer = stateService.requireActiveServer(); + LOGGER.info("PUT /api/client/server-config, request={}, target={}", request, activeServer); + ServerConfigDto config = serverApiService.updateServerConfig(activeServer, request.backupLocation(), request.retentionCount()); + if (request.backupInterval() == null) { + return config; + } + ServerStatusDto status = serverApiService.updateServerSchedule(activeServer, request.backupInterval()); + return new ServerConfigDto(config.backupLocation(), config.retentionCount(), status.backupInterval()); + } + + @GetMapping("/services") + public List services() { + String activeServer = stateService.requireActiveServer(); + LOGGER.info("GET /api/client/services, forwarding to {}", activeServer); + return serverApiService.listServices(activeServer); + } + + @PostMapping("/services") + @ResponseStatus(HttpStatus.CREATED) + public ServiceDto addService(@RequestBody ServiceDto service) { + String activeServer = stateService.requireActiveServer(); + LOGGER.info("POST /api/client/services, name={}, target={}", service.name(), activeServer); + return serverApiService.addService(activeServer, service); + } + + @PutMapping("/services/{name}") + public ServiceDto updateService(@PathVariable String name, @RequestBody ServiceDto service) { + String activeServer = stateService.requireActiveServer(); + LOGGER.info("PUT /api/client/services/{}, name={}, target={}", name, service.name(), activeServer); + return serverApiService.updateService(activeServer, name, service); + } + + @DeleteMapping("/services/{name}") + @ResponseStatus(HttpStatus.NO_CONTENT) + public void removeService(@PathVariable String name) { + String activeServer = stateService.requireActiveServer(); + LOGGER.info("DELETE /api/client/services/{}, target={}", name, activeServer); + serverApiService.removeService(activeServer, name); + } +} diff --git a/src/main/java/wellatleastitried/mediaguardclient/dto/BackupDto.java b/src/main/java/wellatleastitried/mediagarrdclient/dto/BackupDto.java similarity index 100% rename from src/main/java/wellatleastitried/mediaguardclient/dto/BackupDto.java rename to src/main/java/wellatleastitried/mediagarrdclient/dto/BackupDto.java diff --git a/src/main/java/wellatleastitried/mediaguardclient/dto/ClientStatusDto.java b/src/main/java/wellatleastitried/mediagarrdclient/dto/ClientStatusDto.java similarity index 100% rename from src/main/java/wellatleastitried/mediaguardclient/dto/ClientStatusDto.java rename to src/main/java/wellatleastitried/mediagarrdclient/dto/ClientStatusDto.java diff --git a/src/main/java/wellatleastitried/mediaguardclient/dto/ConnectionStatusDto.java b/src/main/java/wellatleastitried/mediagarrdclient/dto/ConnectionStatusDto.java similarity index 100% rename from src/main/java/wellatleastitried/mediaguardclient/dto/ConnectionStatusDto.java rename to src/main/java/wellatleastitried/mediagarrdclient/dto/ConnectionStatusDto.java diff --git a/src/main/java/wellatleastitried/mediaguardclient/dto/IntervalUpdateRequest.java b/src/main/java/wellatleastitried/mediagarrdclient/dto/IntervalUpdateRequest.java similarity index 100% rename from src/main/java/wellatleastitried/mediaguardclient/dto/IntervalUpdateRequest.java rename to src/main/java/wellatleastitried/mediagarrdclient/dto/IntervalUpdateRequest.java diff --git a/src/main/java/wellatleastitried/mediaguardclient/dto/PickupProgressDto.java b/src/main/java/wellatleastitried/mediagarrdclient/dto/PickupProgressDto.java similarity index 100% rename from src/main/java/wellatleastitried/mediaguardclient/dto/PickupProgressDto.java rename to src/main/java/wellatleastitried/mediagarrdclient/dto/PickupProgressDto.java diff --git a/src/main/java/wellatleastitried/mediaguardclient/dto/PickupStartDto.java b/src/main/java/wellatleastitried/mediagarrdclient/dto/PickupStartDto.java similarity index 100% rename from src/main/java/wellatleastitried/mediaguardclient/dto/PickupStartDto.java rename to src/main/java/wellatleastitried/mediagarrdclient/dto/PickupStartDto.java diff --git a/src/main/java/wellatleastitried/mediagarrdclient/dto/ServerConfigDto.java b/src/main/java/wellatleastitried/mediagarrdclient/dto/ServerConfigDto.java new file mode 100644 index 0000000..0d0b8fe --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/dto/ServerConfigDto.java @@ -0,0 +1,6 @@ +package wellatleastitried.mediagarrdclient.dto; + +import java.time.Duration; + +public record ServerConfigDto(String backupLocation, Integer retentionCount, Duration backupInterval) { +} diff --git a/src/main/java/wellatleastitried/mediaguardclient/dto/ServerSelectionRequest.java b/src/main/java/wellatleastitried/mediagarrdclient/dto/ServerSelectionRequest.java similarity index 100% rename from src/main/java/wellatleastitried/mediaguardclient/dto/ServerSelectionRequest.java rename to src/main/java/wellatleastitried/mediagarrdclient/dto/ServerSelectionRequest.java diff --git a/src/main/java/wellatleastitried/mediaguardclient/dto/ServerStatusDto.java b/src/main/java/wellatleastitried/mediagarrdclient/dto/ServerStatusDto.java similarity index 100% rename from src/main/java/wellatleastitried/mediaguardclient/dto/ServerStatusDto.java rename to src/main/java/wellatleastitried/mediagarrdclient/dto/ServerStatusDto.java diff --git a/src/main/java/wellatleastitried/mediagarrdclient/dto/ServiceDto.java b/src/main/java/wellatleastitried/mediagarrdclient/dto/ServiceDto.java new file mode 100644 index 0000000..fdaf639 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/dto/ServiceDto.java @@ -0,0 +1,6 @@ +package wellatleastitried.mediagarrdclient.dto; + +import java.util.List; + +public record ServiceDto(String name, List paths) { +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/BackupPickupService.java b/src/main/java/wellatleastitried/mediagarrdclient/service/BackupPickupService.java new file mode 100644 index 0000000..cee0e67 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/BackupPickupService.java @@ -0,0 +1,275 @@ +package wellatleastitried.mediagarrdclient.service; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.stream.Stream; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Service; +import org.springframework.web.server.ResponseStatusException; + +import jakarta.annotation.PreDestroy; +import wellatleastitried.mediagarrdclient.Configuration; +import wellatleastitried.mediagarrdclient.dto.BackupDto; +import wellatleastitried.mediagarrdclient.dto.PickupProgressDto; +import wellatleastitried.mediagarrdclient.dto.PickupStartDto; + +@Service +public class BackupPickupService { + + private static final Logger LOGGER = LoggerFactory.getLogger(BackupPickupService.class); + private static final String AUTO_DOWNLOAD_SUFFIX = "-AD"; + private static final String ZIP_SUFFIX = ".zip"; + static final Duration FINISHED_TASK_RETENTION = Duration.ofMinutes(10); + + private enum PickupStatus { QUEUED, RUNNING, COMPLETED, FAILED } + + private final class PickupTask { + private final String taskId = UUID.randomUUID().toString(); + private final BackupDto backup; + private volatile PickupStatus status = PickupStatus.QUEUED; + private volatile long bytesWritten; + private volatile long totalBytes; + private volatile Path savedPath; + private volatile String error; + private volatile Instant finishedAt; + + private PickupTask(BackupDto backup) { + this.backup = backup; + this.totalBytes = backup.sizeBytes(); + } + + private boolean finished() { + return finishedAt != null; + } + + private void complete(Path path) { + savedPath = path; + bytesWritten = Math.max(bytesWritten, totalBytes); + totalBytes = Math.max(totalBytes, bytesWritten); + status = PickupStatus.COMPLETED; + finishedAt = clock.instant(); + } + + private void fail(String message) { + error = message; + status = PickupStatus.FAILED; + finishedAt = clock.instant(); + } + + private PickupStartDto started() { + return new PickupStartDto(taskId, backup.id(), backup.fileName(), totalBytes); + } + + private PickupProgressDto progress() { + return new PickupProgressDto(taskId, status.name(), backup.id(), backup.fileName(), bytesWritten, totalBytes, + savedPath == null ? null : savedPath.toString(), error); + } + } + + private final Configuration configuration; + private final ClientStateService clientStateService; + private final ServerApiService serverApiService; + private final Clock clock; + private final ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor(); + private final Map tasks = new LinkedHashMap<>(); + private volatile Instant nextPickup; + + @Autowired + public BackupPickupService(Configuration configuration, ClientStateService clientStateService, ServerApiService serverApiService) { + this(configuration, clientStateService, serverApiService, Clock.systemUTC()); + } + + BackupPickupService(Configuration configuration, ClientStateService clientStateService, ServerApiService serverApiService, Clock clock) { + this.configuration = configuration; + this.clientStateService = clientStateService; + this.serverApiService = serverApiService; + this.clock = clock; + this.nextPickup = clock.instant().plus(clientStateService.getPickupInterval()); + } + + @Scheduled(fixedDelay = 60_000) + public void scheduledPickup() { + Instant now = clock.instant(); + if (now.isBefore(nextPickup)) { + return; + } + nextPickup = now.plus(clientStateService.getPickupInterval()); + try { + LOGGER.info("Scheduled pickup saved {}, next pickup at {}", pickupLatestAuto(), nextPickup); + } catch (RuntimeException e) { + LOGGER.warn("Scheduled pickup failed, next attempt at {}: {}", nextPickup, e.getMessage()); + } + } + + public Duration updatePickupInterval(Duration interval) { + Duration updated = clientStateService.setPickupInterval(interval); + nextPickup = clock.instant().plus(updated); + return updated; + } + + public PickupStartDto startPickupLatestTask() { + String server = clientStateService.requireActiveServer(); + return startPickupTask(server, latest(serverApiService.listBackups(server))); + } + + public PickupStartDto startPickupByIdTask(String backupId) { + String server = clientStateService.requireActiveServer(); + BackupDto backup = serverApiService.listBackups(server).stream() + .filter(candidate -> candidate.id().equals(backupId)) + .findFirst() + .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Backup not found: " + backupId)); + return startPickupTask(server, backup); + } + + public synchronized PickupProgressDto pickupProgress(String taskId) { + PickupTask task = tasks.get(taskId); + if (task == null) { + throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Pickup task not found: " + taskId); + } + return task.progress(); + } + + private synchronized PickupStartDto startPickupTask(String server, BackupDto backup) { + evictFinishedTasks(); + PickupTask running = tasks.values().stream() + .filter(task -> !task.finished() && task.backup.id().equals(backup.id())) + .findFirst() + .orElse(null); + if (running != null) { + LOGGER.info("Backup {} is already being downloaded by task {}", backup.id(), running.taskId); + return running.started(); + } + + PickupTask task = new PickupTask(backup); + tasks.put(task.taskId, task); + Path downloads = downloadsDirectory(); + Path existing = existingCopy(downloads, backup); + if (existing != null) { + LOGGER.info("Backup {} is already downloaded at {}", backup.id(), existing); + task.complete(existing); + } else { + executor.submit(() -> download(server, inside(downloads, backup.fileName()), task)); + } + return task.started(); + } + + private void download(String server, Path destination, PickupTask task) { + task.status = PickupStatus.RUNNING; + try { + Path saved = serverApiService.downloadById(server, task.backup.id(), destination, (written, total) -> { + task.bytesWritten = written; + if (total > 0) { + task.totalBytes = total; + } + }); + task.complete(saved); + LOGGER.info("Pickup task {} saved {}", task.taskId, saved); + } catch (RuntimeException e) { + task.fail(e.getMessage()); + LOGGER.warn("Pickup task {} failed for backup {}: {}", task.taskId, task.backup.id(), e.getMessage()); + } + } + + private void evictFinishedTasks() { + Instant cutoff = clock.instant().minus(FINISHED_TASK_RETENTION); + tasks.values().removeIf(task -> task.finished() && task.finishedAt.isBefore(cutoff)); + } + + private Path pickupLatestAuto() { + String server = clientStateService.requireActiveServer(); + List backups = serverApiService.listBackups(server); + BackupDto latest = latest(backups); + Path downloads = downloadsDirectory(); + Path existing = existingCopy(downloads, latest); + if (existing != null) { + LOGGER.info("Scheduled pickup skipped, backup {} is already downloaded at {}", latest.id(), existing); + return existing; + } + + Path downloaded = serverApiService.downloadById(server, latest.id(), inside(downloads, autoFileName(latest)), null); + deleteIfSameSize(inside(downloads, latest.fileName()), latest); + if (backups.size() > 1) { + deleteQuietly(inside(downloads, autoFileName(backups.get(1)))); + } + return downloaded; + } + + private Path existingCopy(Path downloads, BackupDto backup) { + return Stream.of(autoFileName(backup), backup.fileName()) + .map(name -> inside(downloads, name)) + .filter(path -> hasSize(path, backup.sizeBytes())) + .findFirst() + .orElse(null); + } + + private void deleteIfSameSize(Path path, BackupDto backup) { + if (hasSize(path, backup.sizeBytes())) { + deleteQuietly(path); + } + } + + private static boolean hasSize(Path path, long size) { + try { + return Files.isRegularFile(path) && Files.size(path) == size; + } catch (IOException e) { + LOGGER.warn("Could not inspect {}: {}", path, e.getMessage()); + return false; + } + } + + private static void deleteQuietly(Path path) { + try { + if (Files.deleteIfExists(path)) { + LOGGER.info("Removed superseded download {}", path.getFileName()); + } + } catch (IOException e) { + LOGGER.warn("Could not remove {}: {}", path, e.getMessage()); + } + } + + private static BackupDto latest(List backups) { + if (backups.isEmpty()) { + throw new ResponseStatusException(HttpStatus.NOT_FOUND, "No backups found on server"); + } + return backups.getFirst(); + } + + private static String autoFileName(BackupDto backup) { + String name = backup.fileName(); + return name.endsWith(ZIP_SUFFIX) + ? name.substring(0, name.length() - ZIP_SUFFIX.length()) + AUTO_DOWNLOAD_SUFFIX + ZIP_SUFFIX + : name + AUTO_DOWNLOAD_SUFFIX; + } + + private static Path inside(Path downloads, String fileName) { + Path path = downloads.resolve(fileName).normalize(); + if (!downloads.equals(path.getParent())) { + throw new IllegalArgumentException("Backup file name must not leave the download directory: " + fileName); + } + return path; + } + + private Path downloadsDirectory() { + return Path.of(configuration.getDownloadDirectory()).toAbsolutePath().normalize(); + } + + @PreDestroy + void shutdown() { + executor.shutdownNow(); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/ClientStateService.java b/src/main/java/wellatleastitried/mediagarrdclient/service/ClientStateService.java new file mode 100644 index 0000000..258c718 --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/ClientStateService.java @@ -0,0 +1,137 @@ +package wellatleastitried.mediagarrdclient.service; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.time.Duration; +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Service; +import org.springframework.web.server.ResponseStatusException; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.databind.ObjectMapper; + +import wellatleastitried.mediagarrdclient.Configuration; + +@Service +public class ClientStateService { + + private static final Logger LOGGER = LoggerFactory.getLogger(ClientStateService.class); + private static final Duration DEFAULT_PICKUP_INTERVAL = Duration.ofHours(12); + + @JsonIgnoreProperties(ignoreUnknown = true) + record ClientState(String activeServer, long pickupIntervalSeconds, List knownServers) { + } + + private final Path statePath; + private final ObjectMapper mapper; + private final Set knownServers = new LinkedHashSet<>(); + private String activeServer; + private Duration pickupInterval; + + public ClientStateService(Configuration configuration, ObjectMapper mapper) { + this.statePath = Path.of(configuration.getStateFile()).toAbsolutePath().normalize(); + this.mapper = mapper; + this.pickupInterval = valid(configuration.getPickupInterval()) ? configuration.getPickupInterval() : DEFAULT_PICKUP_INTERVAL; + load(); + LOGGER.info("Client state: activeServer={}, pickupInterval={}, knownServers={}", activeServer, pickupInterval, knownServers); + } + + public synchronized String getActiveServer() { + return activeServer; + } + + public synchronized String requireActiveServer() { + if (isBlank(activeServer)) { + throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "No active MediaGarrd server selected"); + } + return activeServer; + } + + public synchronized Duration getPickupInterval() { + return pickupInterval; + } + + public synchronized List getKnownServers() { + return List.copyOf(knownServers); + } + + public synchronized void updateKnownServers(List servers) { + knownServers.clear(); + knownServers.addAll(servers); + if (isBlank(activeServer)) { + activeServer = knownServers.stream().findFirst().orElse(null); + } else { + knownServers.add(activeServer); + } + LOGGER.info("Known servers updated: {}, active server: {}", knownServers, activeServer); + save(); + } + + public synchronized void setActiveServer(String serverUrl) { + LOGGER.info("Active server changed: {} -> {}", activeServer, serverUrl); + activeServer = serverUrl; + if (!isBlank(serverUrl)) { + knownServers.add(serverUrl); + } + save(); + } + + public synchronized Duration setPickupInterval(Duration interval) { + if (!valid(interval)) { + throw new IllegalArgumentException("Pickup interval must be a positive duration"); + } + pickupInterval = interval; + LOGGER.info("Pickup interval updated to {}", interval); + save(); + return interval; + } + + private void load() { + if (!Files.exists(statePath)) { + LOGGER.info("No state file at {}, starting fresh", statePath); + return; + } + try { + ClientState state = mapper.readValue(statePath.toFile(), ClientState.class); + if (state.knownServers() != null) { + knownServers.addAll(state.knownServers()); + } + activeServer = isBlank(state.activeServer()) ? knownServers.stream().findFirst().orElse(null) : state.activeServer(); + Duration saved = Duration.ofSeconds(state.pickupIntervalSeconds()); + if (valid(saved)) { + pickupInterval = saved; + } + } catch (IOException e) { + LOGGER.warn("Could not read state from {}, starting with defaults: {}", statePath, e.getMessage()); + } + } + + private void save() { + try { + Files.createDirectories(statePath.getParent()); + Path temp = statePath.resolveSibling(statePath.getFileName() + ".tmp"); + ClientState state = new ClientState(activeServer == null ? "" : activeServer, pickupInterval.toSeconds(), new ArrayList<>(knownServers)); + mapper.writerWithDefaultPrettyPrinter().writeValue(temp.toFile(), state); + Files.move(temp, statePath, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); + } catch (IOException e) { + throw new IllegalStateException("Failed to save client state to " + statePath, e); + } + } + + private static boolean valid(Duration duration) { + return duration != null && duration.isPositive(); + } + + private static boolean isBlank(String value) { + return value == null || value.isBlank(); + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/ServerApiService.java b/src/main/java/wellatleastitried/mediagarrdclient/service/ServerApiService.java new file mode 100644 index 0000000..f6db95b --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/ServerApiService.java @@ -0,0 +1,224 @@ +package wellatleastitried.mediagarrdclient.service; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.time.Duration; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.MediaType; +import org.springframework.http.client.JdkClientHttpRequestFactory; +import org.springframework.stereotype.Service; +import org.springframework.web.client.RestClient; +import org.springframework.web.util.UriUtils; + +import wellatleastitried.mediagarrdclient.api.Endpoints; +import wellatleastitried.mediagarrdclient.dto.BackupDto; +import wellatleastitried.mediagarrdclient.dto.ServerConfigDto; +import wellatleastitried.mediagarrdclient.dto.ServerStatusDto; +import wellatleastitried.mediagarrdclient.dto.ServiceDto; + +@Service +public class ServerApiService { + + @FunctionalInterface + public interface DownloadProgressListener { + void onProgress(long bytesWritten, long totalBytes); + } + + private static final Logger LOGGER = LoggerFactory.getLogger(ServerApiService.class); + private static final String SERVICE_PATH = Endpoints.SERVER_SERVICES.getPath() + "/{name}"; + private static final Duration CONNECT_TIMEOUT = Duration.ofSeconds(3); + private static final Duration HEALTH_TIMEOUT = Duration.ofSeconds(5); + private static final Duration REQUEST_TIMEOUT = Duration.ofSeconds(30); + private static final int BUFFER_SIZE = 64 * 1024; + + private final HttpClient httpClient = HttpClient.newBuilder() + .connectTimeout(CONNECT_TIMEOUT) + .followRedirects(HttpClient.Redirect.NORMAL) + .build(); + private final RestClient healthClient = restClient(HEALTH_TIMEOUT); + private final RestClient restClient = restClient(REQUEST_TIMEOUT); + private final RestClient backupRunClient = restClient(null); + + private RestClient restClient(Duration readTimeout) { + JdkClientHttpRequestFactory requestFactory = new JdkClientHttpRequestFactory(httpClient); + if (readTimeout != null) { + requestFactory.setReadTimeout(readTimeout); + } + return RestClient.builder().requestFactory(requestFactory).build(); + } + + public ServerStatusDto health(String serverUrl) { + ServerStatusDto status = healthClient.get() + .uri(serverUrl + Endpoints.SERVER_HEALTH.getPath()) + .retrieve() + .body(ServerStatusDto.class); + LOGGER.debug("Server health of {}: {}", serverUrl, status); + return status; + } + + public List listBackups(String serverUrl) { + List backups = restClient.get() + .uri(serverUrl + Endpoints.SERVER_BACKUPS.getPath()) + .retrieve() + .body(new ParameterizedTypeReference<>() {}); + LOGGER.debug("Received {} backup(s) from {}", backups == null ? 0 : backups.size(), serverUrl); + return backups == null ? List.of() : backups; + } + + public void triggerBackup(String serverUrl) { + LOGGER.info("Triggering backup on {}", serverUrl); + backupRunClient.post() + .uri(serverUrl + Endpoints.SERVER_BACKUP_RUN.getPath()) + .retrieve() + .toBodilessEntity(); + LOGGER.info("Backup finished on {}", serverUrl); + } + + public ServerStatusDto updateServerSchedule(String serverUrl, Duration interval) { + LOGGER.info("Updating server schedule on {} to {}", serverUrl, interval); + return restClient.put() + .uri(serverUrl + Endpoints.SERVER_SCHEDULE.getPath()) + .contentType(MediaType.APPLICATION_JSON) + .body(Map.of("backupInterval", interval.toString())) + .retrieve() + .body(ServerStatusDto.class); + } + + public ServerConfigDto serverConfig(String serverUrl) { + return restClient.get() + .uri(serverUrl + Endpoints.SERVER_CONFIG.getPath()) + .retrieve() + .body(ServerConfigDto.class); + } + + public ServerConfigDto updateServerConfig(String serverUrl, String backupLocation, Integer retentionCount) { + LOGGER.info("Updating server configuration on {}: backupLocation={}, retentionCount={}", serverUrl, backupLocation, retentionCount); + Map body = new HashMap<>(); + body.put("backupLocation", backupLocation); + body.put("retentionCount", retentionCount); + return restClient.put() + .uri(serverUrl + Endpoints.SERVER_CONFIG.getPath()) + .contentType(MediaType.APPLICATION_JSON) + .body(body) + .retrieve() + .body(ServerConfigDto.class); + } + + public List listServices(String serverUrl) { + List services = restClient.get() + .uri(serverUrl + Endpoints.SERVER_SERVICES.getPath()) + .retrieve() + .body(new ParameterizedTypeReference<>() {}); + return services == null ? List.of() : services; + } + + public ServiceDto addService(String serverUrl, ServiceDto service) { + LOGGER.info("Adding service {} on {}", service.name(), serverUrl); + return restClient.post() + .uri(serverUrl + Endpoints.SERVER_SERVICES.getPath()) + .contentType(MediaType.APPLICATION_JSON) + .body(service) + .retrieve() + .body(ServiceDto.class); + } + + public ServiceDto updateService(String serverUrl, String name, ServiceDto service) { + LOGGER.info("Updating service {} on {}", name, serverUrl); + return restClient.put() + .uri(serverUrl + SERVICE_PATH, name) + .contentType(MediaType.APPLICATION_JSON) + .body(service) + .retrieve() + .body(ServiceDto.class); + } + + public void removeService(String serverUrl, String name) { + LOGGER.info("Removing service {} from {}", name, serverUrl); + restClient.delete() + .uri(serverUrl + SERVICE_PATH, name) + .retrieve() + .toBodilessEntity(); + } + + public Path downloadById(String serverUrl, String backupId, Path destination, DownloadProgressListener progressListener) { + URI uri = URI.create(serverUrl + Endpoints.SERVER_BACKUPS.getPath() + "/" + UriUtils.encodePathSegment(backupId, StandardCharsets.UTF_8) + "/download"); + LOGGER.info("Downloading backup {} from {} to {}", backupId, serverUrl, destination); + Path temp = destination.resolveSibling(destination.getFileName() + ".part"); + try { + HttpResponse response = httpClient.send(HttpRequest.newBuilder(uri).GET().build(), HttpResponse.BodyHandlers.ofInputStream()); + try (InputStream body = response.body()) { + if (response.statusCode() / 100 != 2) { + String snippet = new String(body.readNBytes(256), StandardCharsets.UTF_8); + LOGGER.error("Download of backup {} failed with HTTP {}: {}", backupId, response.statusCode(), snippet); + throw new IllegalStateException("Download of backup " + backupId + " failed with HTTP " + response.statusCode()); + } + Files.createDirectories(destination.getParent()); + long totalBytes = response.headers().firstValueAsLong("Content-Length").orElse(-1L); + copy(body, temp, totalBytes, progressListener); + } + if (!looksLikeZip(temp)) { + throw new IllegalStateException("Server returned non-zip content for backup " + backupId); + } + Files.move(temp, destination, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); + LOGGER.info("Downloaded backup {} to {} ({} bytes)", backupId, destination, Files.size(destination)); + return destination; + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Download of backup " + backupId + " was interrupted", e); + } catch (IOException e) { + LOGGER.error("Failed to save backup {} to {}", backupId, destination, e); + throw new IllegalStateException("Failed to save backup " + backupId + ": " + e.getMessage(), e); + } finally { + deleteQuietly(temp); + } + } + + private static void copy(InputStream in, Path target, long totalBytes, DownloadProgressListener progressListener) throws IOException { + try (OutputStream out = Files.newOutputStream(target)) { + byte[] buffer = new byte[BUFFER_SIZE]; + long written = 0; + int read; + while ((read = in.read(buffer)) != -1) { + out.write(buffer, 0, read); + written += read; + if (progressListener != null) { + progressListener.onProgress(written, totalBytes); + } + } + } + } + + private static boolean looksLikeZip(Path path) throws IOException { + byte[] header = new byte[4]; + try (InputStream in = Files.newInputStream(path)) { + if (in.readNBytes(header, 0, 4) < 4) { + return false; + } + } + return header[0] == 'P' && header[1] == 'K' + && ((header[2] == 3 && header[3] == 4) || (header[2] == 5 && header[3] == 6) || (header[2] == 7 && header[3] == 8)); + } + + private static void deleteQuietly(Path path) { + try { + Files.deleteIfExists(path); + } catch (IOException e) { + LOGGER.warn("Could not delete {}: {}", path, e.getMessage()); + } + } +} diff --git a/src/main/java/wellatleastitried/mediagarrdclient/service/ServerDiscoveryService.java b/src/main/java/wellatleastitried/mediagarrdclient/service/ServerDiscoveryService.java new file mode 100644 index 0000000..ed9fbdd --- /dev/null +++ b/src/main/java/wellatleastitried/mediagarrdclient/service/ServerDiscoveryService.java @@ -0,0 +1,319 @@ +package wellatleastitried.mediagarrdclient.service; + +import java.io.IOException; +import java.net.ConnectException; +import java.net.Inet4Address; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.InterfaceAddress; +import java.net.NetworkInterface; +import java.net.Socket; +import java.net.SocketException; +import java.net.UnknownHostException; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.time.Duration; +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Semaphore; +import java.util.stream.IntStream; +import java.util.stream.Stream; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Service; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import jakarta.annotation.PreDestroy; +import wellatleastitried.mediagarrdclient.Configuration; +import wellatleastitried.mediagarrdclient.api.Endpoints; + +@Service +public class ServerDiscoveryService { + + private static final Logger LOGGER = LoggerFactory.getLogger(ServerDiscoveryService.class); + + private static final List COMMON_PORTS = List.of(38471, 8080, 80); + private static final List VIRTUAL_INTERFACE_PREFIXES = List.of("docker", "br-", "veth", "virbr", "vmnet", "vboxnet", "cni", "flannel", "cali", "tun", "tap", "wg", "zt", "tailscale"); + private static final int MIN_SCAN_PREFIX_LENGTH = 24; + private static final int FIRST_UNPRIVILEGED_PORT = 1024; + private static final int MAX_PORT = 65535; + private static final int MAX_CONCURRENT_PROBES = 256; + private static final Duration CONNECT_TIMEOUT = Duration.ofMillis(500); + private static final Duration HEALTH_TIMEOUT = Duration.ofSeconds(2); + private static final Duration SCAN_DEADLINE = Duration.ofSeconds(20); + + enum Probe { OPEN, REFUSED, UNREACHABLE } + + record Candidate(String host, InetAddress address, int port) { + String url() { + return "http://" + (host.contains(":") ? "[" + host + "]" : host) + ":" + port; + } + } + + record HostInput(String host, Integer port) { + } + + private record ProbeResult(Probe probe, String server) { + } + + private record QuickResult(Optional server, boolean hostAlive) { + } + + private final Configuration configuration; + private final ClientStateService stateService; + private final ObjectMapper mapper; + private final HttpClient httpClient = HttpClient.newBuilder() + .connectTimeout(CONNECT_TIMEOUT.multipliedBy(2)) + .followRedirects(HttpClient.Redirect.NEVER) + .build(); + private final ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor(); + private final Semaphore probeSlots = new Semaphore(MAX_CONCURRENT_PROBES); + + public ServerDiscoveryService(Configuration configuration, ClientStateService stateService, ObjectMapper mapper) { + this.configuration = configuration; + this.stateService = stateService; + this.mapper = mapper; + } + + @Scheduled(fixedDelay = 30_000) + public void connectPreferredServer() { + String active = stateService.getActiveServer(); + if (active == null || active.isBlank()) { + resolvePreferredServer().ifPresent(stateService::setActiveServer); + } + } + + public List discover() { + long start = System.nanoTime(); + Set discovered = new LinkedHashSet<>(); + resolvePreferredServer().ifPresent(discovered::add); + + List hosts = localSubnetHosts(); + List ports = quickPorts(null); + List candidates = hosts.stream() + .flatMap(host -> ports.stream().map(port -> new Candidate(host.getHostAddress(), host, port))) + .toList(); + LOGGER.info("Scanning {} host(s) on ports {} ({} candidates)", hosts.size(), ports, candidates.size()); + discovered.addAll(findServers(candidates, deadline())); + + LOGGER.info("Network discovery found {} server(s) in {} ms: {}", discovered.size(), elapsedMillis(start), discovered); + return List.copyOf(discovered); + } + + public Optional resolvePreferredServer() { + String preferred = configuration.getPreferredServerIp(); + if (preferred == null || preferred.isBlank()) { + return Optional.empty(); + } + HostInput input = parseHost(preferred); + InetAddress address = input == null ? null : resolve(input.host()); + return address == null ? Optional.empty() : quickResolve(input.host(), address, input.port(), deadline()).server(); + } + + public Optional resolveServerByIp(String input, Integer port) { + HostInput parsed = parseHost(input); + InetAddress address = parsed == null ? null : resolve(parsed.host()); + if (address == null) { + LOGGER.warn("Cannot resolve a server from '{}'", input); + return Optional.empty(); + } + Integer preferredPort = port != null ? port : parsed.port(); + long deadline = deadline(); + QuickResult quick = quickResolve(parsed.host(), address, preferredPort, deadline); + if (quick.server().isPresent() || !quick.hostAlive()) { + return quick.server(); + } + + LOGGER.info("No MediaGarrd server on the common ports of {}, scanning ports {}-{}", parsed.host(), FIRST_UNPRIVILEGED_PORT, MAX_PORT); + long start = System.nanoTime(); + Set probed = Set.copyOf(quickPorts(preferredPort)); + List candidates = IntStream.rangeClosed(FIRST_UNPRIVILEGED_PORT, MAX_PORT) + .filter(candidatePort -> !probed.contains(candidatePort)) + .mapToObj(candidatePort -> new Candidate(parsed.host(), address, candidatePort)) + .toList(); + Optional found = findServers(candidates, deadline).stream().findFirst(); + LOGGER.info("Port scan of {} finished in {} ms: {}", parsed.host(), elapsedMillis(start), found.orElse("no server found")); + return found; + } + + private QuickResult quickResolve(String host, InetAddress address, Integer preferredPort, long deadline) { + List> probes = quickPorts(preferredPort).stream() + .map(port -> probeAsync(new Candidate(host, address, port), deadline)) + .toList(); + List results = probes.stream().map(CompletableFuture::join).toList(); + Optional server = results.stream().map(ProbeResult::server).filter(Objects::nonNull).findFirst(); + boolean alive = results.stream().anyMatch(result -> result.probe() != Probe.UNREACHABLE); + server.ifPresentOrElse( + url -> LOGGER.info("Resolved MediaGarrd server at {}", url), + () -> LOGGER.debug("No MediaGarrd server on the common ports of {} (host {})", host, alive ? "reachable" : "unreachable")); + return new QuickResult(server, alive); + } + + private List findServers(List candidates, long deadline) { + List> probes = candidates.stream().map(candidate -> probeAsync(candidate, deadline)).toList(); + return probes.stream() + .map(CompletableFuture::join) + .map(ProbeResult::server) + .filter(Objects::nonNull) + .distinct() + .toList(); + } + + private CompletableFuture probeAsync(Candidate candidate, long deadline) { + return CompletableFuture.supplyAsync(() -> { + Probe probe = connect(candidate, deadline); + return new ProbeResult(probe, probe == Probe.OPEN && isMediaGarrdServer(candidate) ? candidate.url() : null); + }, executor); + } + + private Probe connect(Candidate candidate, long deadline) { + try { + probeSlots.acquire(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return Probe.UNREACHABLE; + } + try (Socket socket = new Socket()) { + if (System.nanoTime() > deadline) { + return Probe.UNREACHABLE; + } + socket.connect(new InetSocketAddress(candidate.address(), candidate.port()), (int) CONNECT_TIMEOUT.toMillis()); + return Probe.OPEN; + } catch (ConnectException e) { + return e.getMessage() != null && e.getMessage().contains("refused") ? Probe.REFUSED : Probe.UNREACHABLE; + } catch (IOException | IllegalArgumentException e) { + return Probe.UNREACHABLE; + } finally { + probeSlots.release(); + } + } + + boolean isMediaGarrdServer(Candidate candidate) { + HttpRequest request = HttpRequest.newBuilder(URI.create(candidate.url() + Endpoints.SERVER_HEALTH.getPath())) + .timeout(HEALTH_TIMEOUT) + .GET() + .build(); + try { + HttpResponse response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); + if (response.statusCode() != 200) { + return false; + } + JsonNode health = mapper.readTree(response.body()); + return health.path("healthy").isBoolean() && health.has("backupInterval"); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return false; + } catch (IOException | IllegalArgumentException e) { + LOGGER.debug("{} is not a MediaGarrd server: {}", candidate.url(), e.getMessage()); + return false; + } + } + + private List quickPorts(Integer preferredPort) { + return Stream.concat(Stream.of(preferredPort, configuration.getServerPort()), COMMON_PORTS.stream()) + .filter(Objects::nonNull) + .distinct() + .toList(); + } + + private List localSubnetHosts() { + Set hosts = new LinkedHashSet<>(); + try { + for (NetworkInterface networkInterface : NetworkInterface.networkInterfaces().toList()) { + if (!networkInterface.isUp() || networkInterface.isLoopback() || networkInterface.isVirtual() || isVirtualBridge(networkInterface)) { + continue; + } + for (InterfaceAddress address : networkInterface.getInterfaceAddresses()) { + if (address.getAddress() instanceof Inet4Address ipv4) { + hosts.addAll(subnetHosts(ipv4, address.getNetworkPrefixLength())); + } + } + } + } catch (SocketException e) { + LOGGER.warn("Could not list network interfaces: {}", e.getMessage()); + } + return List.copyOf(hosts); + } + + static List subnetHosts(Inet4Address address, int prefixLength) { + int prefix = Math.min(Math.max(prefixLength, MIN_SCAN_PREFIX_LENGTH), 30); + int ip = toInt(address.getAddress()); + int mask = -1 << (32 - prefix); + int network = ip & mask; + int broadcast = network | ~mask; + List hosts = new ArrayList<>(broadcast - network - 1); + for (int host = network + 1; host < broadcast; host++) { + hosts.add(toAddress(host)); + } + return hosts; + } + + private static boolean isVirtualBridge(NetworkInterface networkInterface) { + String name = networkInterface.getName(); + return VIRTUAL_INTERFACE_PREFIXES.stream().anyMatch(name::startsWith); + } + + static HostInput parseHost(String input) { + if (input == null || input.isBlank()) { + return null; + } + String trimmed = input.trim(); + try { + URI uri = URI.create(trimmed.contains("://") ? trimmed : "http://" + trimmed); + if (uri.getHost() == null || uri.getHost().isBlank()) { + return null; + } + String host = uri.getHost().startsWith("[") ? uri.getHost().substring(1, uri.getHost().length() - 1) : uri.getHost(); + return new HostInput(host, uri.getPort() > 0 ? uri.getPort() : null); + } catch (IllegalArgumentException e) { + return null; + } + } + + private static int toInt(byte[] bytes) { + return (bytes[0] & 0xFF) << 24 | (bytes[1] & 0xFF) << 16 | (bytes[2] & 0xFF) << 8 | (bytes[3] & 0xFF); + } + + private static InetAddress toAddress(int ip) { + try { + return InetAddress.getByAddress(new byte[] {(byte) (ip >>> 24), (byte) (ip >>> 16), (byte) (ip >>> 8), (byte) ip}); + } catch (UnknownHostException e) { + throw new IllegalStateException(e); + } + } + + private static InetAddress resolve(String host) { + try { + return InetAddress.getByName(host); + } catch (UnknownHostException e) { + LOGGER.debug("Cannot resolve host {}: {}", host, e.getMessage()); + return null; + } + } + + private static long deadline() { + return System.nanoTime() + SCAN_DEADLINE.toNanos(); + } + + private static long elapsedMillis(long start) { + return Duration.ofNanos(System.nanoTime() - start).toMillis(); + } + + @PreDestroy + void shutdown() { + executor.shutdownNow(); + } +} diff --git a/src/main/java/wellatleastitried/mediaguardclient/WebMvcConfig.java b/src/main/java/wellatleastitried/mediaguardclient/WebMvcConfig.java deleted file mode 100644 index dabc55a..0000000 --- a/src/main/java/wellatleastitried/mediaguardclient/WebMvcConfig.java +++ /dev/null @@ -1,22 +0,0 @@ -package wellatleastitried.mediagarrdclient; - -import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; - -@Configuration -public class WebMvcConfig implements WebMvcConfigurer { - - @Override - public void addResourceHandlers(ResourceHandlerRegistry registry) { - registry - .addResourceHandler("/css/**", "/js/**", "/images/**", "/*.png", "/*.ico", "/*.svg") - .addResourceLocations("classpath:/static/") - .setCachePeriod(0); - - registry - .addResourceHandler("/index.html") - .addResourceLocations("classpath:/static/index.html") - .setCachePeriod(0); - } -} diff --git a/src/main/java/wellatleastitried/mediaguardclient/api/ClientController.java b/src/main/java/wellatleastitried/mediaguardclient/api/ClientController.java deleted file mode 100644 index e3fe178..0000000 --- a/src/main/java/wellatleastitried/mediaguardclient/api/ClientController.java +++ /dev/null @@ -1,216 +0,0 @@ -package wellatleastitried.mediagarrdclient.api; - -import java.time.Duration; -import java.util.List; - -import org.springframework.http.HttpStatus; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.PutMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.server.ResponseStatusException; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import wellatleastitried.mediagarrdclient.Configuration; -import wellatleastitried.mediagarrdclient.dto.BackupDto; -import wellatleastitried.mediagarrdclient.dto.ClientStatusDto; -import wellatleastitried.mediagarrdclient.dto.ConnectionStatusDto; -import wellatleastitried.mediagarrdclient.dto.IntervalUpdateRequest; -import wellatleastitried.mediagarrdclient.dto.PickupProgressDto; -import wellatleastitried.mediagarrdclient.dto.PickupStartDto; -import wellatleastitried.mediagarrdclient.dto.ServerSelectionRequest; -import wellatleastitried.mediagarrdclient.dto.ServerStatusDto; -import wellatleastitried.mediagarrdclient.service.BackupPickupService; -import wellatleastitried.mediagarrdclient.service.ClientStateService; -import wellatleastitried.mediagarrdclient.service.ServerApiService; -import wellatleastitried.mediagarrdclient.service.ServerDiscoveryService; - -@RestController -@RequestMapping("/api/client") -public class ClientController { - - private static final Logger LOGGER = LoggerFactory.getLogger(ClientController.class); - - private final Configuration configuration; - private final ClientStateService stateService; - private final ServerDiscoveryService discoveryService; - private final ServerApiService serverApiService; - private final BackupPickupService pickupService; - - public ClientController( - Configuration configuration, - ClientStateService stateService, - ServerDiscoveryService discoveryService, - ServerApiService serverApiService, - BackupPickupService pickupService - ) { - this.configuration = configuration; - this.stateService = stateService; - this.discoveryService = discoveryService; - this.serverApiService = serverApiService; - this.pickupService = pickupService; - } - - @GetMapping("/status") - public ClientStatusDto status() { - LOGGER.info("GET /api/client/status"); - String activeServer = stateService.getActiveServer(); - if (activeServer == null || activeServer.isBlank()) { - String preferredIp = configuration.getPreferredServerIp(); - if (preferredIp != null && !preferredIp.isBlank()) { - LOGGER.info("No active server, probing preferred IP: {}", preferredIp); - discoveryService.resolveServerByIp(preferredIp).ifPresent(url -> { - LOGGER.info("Auto-resolved server from preferred IP: {}", url); - stateService.setActiveServer(url); - }); - } - } - - ClientStatusDto dto = new ClientStatusDto( - stateService.getActiveServer(), - stateService.getPickupInterval(), - stateService.getKnownServers() - ); - LOGGER.info("Status: activeServer={}, pickupInterval={}, knownServers={}", dto.activeServer(), dto.pickupInterval(), dto.knownServers()); - return dto; - } - - @PostMapping("/discover") - public ClientStatusDto discover() { - LOGGER.info("POST /api/client/discover, starting network scan"); - List discovered = discoveryService.discover(); - LOGGER.info("Discovery complete, found {} server(s): {}", discovered.size(), discovered); - stateService.updateKnownServers(discovered); - return status(); - } - - @GetMapping("/server-health") - public ConnectionStatusDto serverHealth() { - LOGGER.info("GET /api/client/server-health"); - String activeServer = stateService.getActiveServer(); - if (activeServer == null || activeServer.isBlank()) { - LOGGER.warn("server-health: no active server configured"); - return new ConnectionStatusDto("", false); - } - - try { - ServerStatusDto serverStatus = serverApiService.health(activeServer); - LOGGER.info("server-health: {} is reachable", activeServer); - return new ConnectionStatusDto(activeServer, true, serverStatus); - } catch (RuntimeException ex) { - LOGGER.warn("server-health: {} is unreachable: {}", activeServer, ex.getMessage()); - return new ConnectionStatusDto(activeServer, false); - } - } - - @PutMapping("/server") - public ClientStatusDto setServer(@RequestBody ServerSelectionRequest request) { - LOGGER.info("PUT /api/client/server, request={}", request); - if (request == null) { - throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Request body is required"); - } - - String requestedUrl = request.serverUrl(); - if (requestedUrl != null && !requestedUrl.isBlank()) { - LOGGER.info("Setting active server by URL: {}", requestedUrl.trim()); - stateService.setActiveServer(requestedUrl.trim()); - return status(); - } - - String serverIp = request.serverIp(); - if (serverIp == null || serverIp.isBlank()) { - throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Either serverUrl or serverIp must be provided"); - } - - Integer serverPort = request.serverPort(); - if (serverPort != null && (serverPort < 1 || serverPort > 65535)) { - throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "serverPort must be between 1 and 65535"); - } - - LOGGER.info("Resolving server by IP={}, port={}", serverIp, serverPort); - String resolved = discoveryService.resolveServerByIp(serverIp, serverPort) - .orElseThrow(() -> { - LOGGER.warn("Unable to resolve server at IP={}, port={}", serverIp, serverPort); - return new ResponseStatusException(HttpStatus.BAD_REQUEST, "Unable to resolve MediaGarrd server on provided IP"); - }); - LOGGER.info("Resolved server: {}", resolved); - stateService.setActiveServer(resolved); - return status(); - } - - @GetMapping("/backups") - public List listBackups() { - String activeServer = requireActiveServer(); - LOGGER.info("GET /api/client/backups, forwarding to {}", activeServer); - List backups = serverApiService.listBackups(activeServer); - LOGGER.info("Received {} backup(s) from server", backups.size()); - return backups; - } - - @PostMapping("/backups/run") - public void runBackup() { - String activeServer = requireActiveServer(); - LOGGER.info("POST /api/client/backups/run, triggering backup on {}", activeServer); - serverApiService.triggerBackup(activeServer); - LOGGER.info("Backup triggered successfully on {}", activeServer); - } - - @PostMapping("/pickup") - public PickupStartDto pickupNow() { - LOGGER.info("POST /api/client/pickup, manual pickup requested"); - PickupStartDto task = pickupService.startPickupLatestTask(); - LOGGER.info("Pickup task started: {}", task.taskId()); - return task; - } - - @PostMapping("/pickup/{id}") - public PickupStartDto pickupById(@PathVariable String id) { - LOGGER.info("POST /api/client/pickup/{}, manual pickup by id requested", id); - PickupStartDto task = pickupService.startPickupByIdTask(id); - LOGGER.info("Pickup-by-id task started: {} for {}", task.taskId(), id); - return task; - } - - @GetMapping("/pickup/progress/{taskId}") - public PickupProgressDto pickupProgress(@PathVariable String taskId) { - LOGGER.debug("GET /api/client/pickup/progress/{}", taskId); - PickupProgressDto progress = pickupService.pickupProgress(taskId); - LOGGER.debug("Pickup progress returned: taskId={}, status={}, bytesWritten={}, totalBytes={}", - taskId, progress.status(), progress.bytesWritten(), progress.totalBytes()); - return progress; - } - - @PutMapping("/pickup-interval") - public ClientStatusDto updatePickupInterval(@RequestBody IntervalUpdateRequest request) { - LOGGER.info("PUT /api/client/pickup-interval, requested={}", request.interval()); - Duration duration = pickupService.updatePickupInterval(request.interval()); - LOGGER.info("Pickup interval updated to: {}", duration); - return new ClientStatusDto( - stateService.getActiveServer(), - duration, - stateService.getKnownServers() - ); - } - - @PutMapping("/server-schedule") - public void updateServerSchedule(@RequestBody IntervalUpdateRequest request) { - String activeServer = requireActiveServer(); - LOGGER.info("PUT /api/client/server-schedule, interval={}, target={}", request.interval(), activeServer); - serverApiService.updateServerSchedule(activeServer, request.interval()); - LOGGER.info("Server schedule updated on {}", activeServer); - } - - private String requireActiveServer() { - String activeServer = stateService.getActiveServer(); - if (activeServer == null || activeServer.isBlank()) { - LOGGER.warn("Request rejected: no active server configured"); - throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "No active MediaGarrd server selected"); - } - return activeServer; - } -} diff --git a/src/main/java/wellatleastitried/mediaguardclient/api/Endpoints.java b/src/main/java/wellatleastitried/mediaguardclient/api/Endpoints.java deleted file mode 100644 index f4ca708..0000000 --- a/src/main/java/wellatleastitried/mediaguardclient/api/Endpoints.java +++ /dev/null @@ -1,28 +0,0 @@ -package wellatleastitried.mediagarrdclient.api; - -public enum Endpoints { - - CLIENT_STATUS("/api/client/status"), - CLIENT_DISCOVER("/api/client/discover"), - CLIENT_SERVER("/api/client/server"), - CLIENT_BACKUPS("/api/client/backups"), - CLIENT_BACKUP_RUN("/api/client/backups/run"), - CLIENT_PICKUP("/api/client/pickup"), - CLIENT_PICKUP_INTERVAL("/api/client/pickup-interval"), - CLIENT_SERVER_SCHEDULE("/api/client/server-schedule"), - SERVER_HEALTH("/api/v1/health"), - SERVER_BACKUPS("/api/v1/backups"), - SERVER_BACKUP_RUN("/api/v1/backups/run"), - SERVER_BACKUP_LATEST_DOWNLOAD("/api/v1/backups/latest/download"), - SERVER_SCHEDULE("/api/v1/schedule"); - - private final String path; - - Endpoints(String path) { - this.path = path; - } - - public String getPath() { - return path; - } -} diff --git a/src/main/java/wellatleastitried/mediaguardclient/api/WebController.java b/src/main/java/wellatleastitried/mediaguardclient/api/WebController.java deleted file mode 100644 index 9a2eb36..0000000 --- a/src/main/java/wellatleastitried/mediaguardclient/api/WebController.java +++ /dev/null @@ -1,13 +0,0 @@ -package wellatleastitried.mediagarrdclient.api; - -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.GetMapping; - -@Controller -public class WebController { - - @GetMapping("/") - public String index() { - return "forward:/index.html"; - } -} diff --git a/src/main/java/wellatleastitried/mediaguardclient/service/BackupPickupService.java b/src/main/java/wellatleastitried/mediaguardclient/service/BackupPickupService.java deleted file mode 100644 index 09dd29f..0000000 --- a/src/main/java/wellatleastitried/mediaguardclient/service/BackupPickupService.java +++ /dev/null @@ -1,330 +0,0 @@ -package wellatleastitried.mediagarrdclient.service; - -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.time.Duration; -import java.time.Instant; -import java.util.List; -import java.util.Map; -import java.util.UUID; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -import jakarta.annotation.PreDestroy; -import org.springframework.scheduling.annotation.Scheduled; -import org.springframework.stereotype.Service; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import wellatleastitried.mediagarrdclient.Configuration; -import wellatleastitried.mediagarrdclient.dto.BackupDto; -import wellatleastitried.mediagarrdclient.dto.PickupProgressDto; -import wellatleastitried.mediagarrdclient.dto.PickupStartDto; - -@Service -public class BackupPickupService { - - private static final Logger LOGGER = LoggerFactory.getLogger(BackupPickupService.class); - private static final String AUTO_DOWNLOAD_SUFFIX = "-AD"; - - private final Configuration configuration; - private final ClientStateService clientStateService; - private final ServerApiService serverApiService; - private final ExecutorService pickupExecutor = Executors.newCachedThreadPool(); - private final Map pickupTasks = new ConcurrentHashMap<>(); - private Instant nextPickup; - - private enum PickupStatus { - QUEUED, - RUNNING, - COMPLETED, - FAILED - } - - private static final class PickupTaskState { - private final String taskId; - private final String backupId; - private final String fileName; - private volatile PickupStatus status; - private volatile long bytesWritten; - private volatile long totalBytes; - private volatile Path savedPath; - private volatile String error; - - private PickupTaskState(String taskId, String backupId, String fileName, long totalBytes) { - this.taskId = taskId; - this.backupId = backupId; - this.fileName = fileName; - this.totalBytes = totalBytes; - this.status = PickupStatus.QUEUED; - this.bytesWritten = 0L; - } - } - - public BackupPickupService( - Configuration configuration, - ClientStateService clientStateService, - ServerApiService serverApiService - ) { - this.configuration = configuration; - this.clientStateService = clientStateService; - this.serverApiService = serverApiService; - this.nextPickup = Instant.now().plus(clientStateService.getPickupInterval()); - } - - @Scheduled(fixedDelay = 60000) - public void scheduledPickup() { - Instant now = Instant.now(); - if (now.isBefore(nextPickup)) { - return; - } - LOGGER.info("Scheduled pickup triggered, next scheduled check was {}", nextPickup); - try { - Path result = pickupLatestAuto(); - LOGGER.info("Scheduled pickup complete: {}", result); - } catch (RuntimeException ex) { - LOGGER.warn("Scheduled pickup failed", ex); - } - nextPickup = now.plus(clientStateService.getPickupInterval()); - LOGGER.info("Next pickup scheduled at: {}", nextPickup); - } - - public Path pickupLatest() { - String activeServer = requireActiveServer(); - List backups = serverApiService.listBackups(activeServer); - BackupDto latest = latestRequired(backups); - - return pickupManual(activeServer, latest); - } - - public PickupStartDto startPickupLatestTask() { - String activeServer = requireActiveServer(); - List backups = serverApiService.listBackups(activeServer); - BackupDto latest = latestRequired(backups); - return startPickupTask(activeServer, latest); - } - - public PickupStartDto startPickupByIdTask(String backupId) { - String activeServer = requireActiveServer(); - return startPickupTask(activeServer, requireBackup(activeServer, backupId)); - } - - public PickupProgressDto pickupProgress(String taskId) { - PickupTaskState state = pickupTasks.get(taskId); - if (state == null) { - LOGGER.warn("Pickup task not found: {}", taskId); - throw new IllegalStateException("Pickup task not found: " + taskId); - } - - LOGGER.debug("Pickup task status requested: taskId={}, status={}, bytesWritten={}, totalBytes={}", - taskId, state.status, state.bytesWritten, state.totalBytes); - - return new PickupProgressDto( - state.taskId, - state.status.name(), - state.backupId, - state.fileName, - state.bytesWritten, - state.totalBytes, - state.savedPath == null ? null : state.savedPath.toString(), - state.error - ); - } - - public Path pickupById(String backupId) { - String activeServer = requireActiveServer(); - return pickupManual(activeServer, requireBackup(activeServer, backupId)); - } - - private Path pickupLatestAuto() { - String activeServer = requireActiveServer(); - List backups = serverApiService.listBackups(activeServer); - BackupDto latest = latestRequired(backups); - - Path downloadsDir = downloadsDirectory(); - Path existingPath = findExistingCopy(downloadsDir, latest); - if (existingPath != null) { - LOGGER.info("Auto pickup skipped for {} because local copy already exists at {}", latest.id(), existingPath); - return existingPath; - } - - Path latestAutoPath = downloadsDir.resolve(withAutoSuffix(latest.fileName())); - LOGGER.info("Auto pickup downloading {} to {}", latest.fileName(), latestAutoPath); - Path downloaded = serverApiService.downloadById(activeServer, latest.id(), latestAutoPath); - deletePlainDuplicate(downloadsDir, latest); - - if (backups.size() > 1) { - BackupDto secondMostRecent = backups.get(1); - Path secondAutoPath = downloadsDir.resolve(withAutoSuffix(secondMostRecent.fileName())); - if (Files.exists(secondAutoPath)) { - try { - Files.deleteIfExists(secondAutoPath); - LOGGER.info("Auto pickup removed second-most-recent auto-downloaded backup {}", secondAutoPath.getFileName()); - } catch (IOException e) { - LOGGER.warn("Auto pickup failed to remove second-most-recent auto-downloaded backup {}", secondAutoPath, e); - } - } - } - - return downloaded; - } - - private Path findExistingCopy(Path downloadsDir, BackupDto backup) { - Path autoPath = downloadsDir.resolve(withAutoSuffix(backup.fileName())); - if (matchesBackup(autoPath, backup)) { - return autoPath; - } - - Path plainPath = downloadsDir.resolve(backup.fileName()); - if (matchesBackup(plainPath, backup)) { - return plainPath; - } - - return null; - } - - private boolean matchesBackup(Path candidate, BackupDto backup) { - if (!Files.exists(candidate)) { - return false; - } - - try { - return Files.size(candidate) == backup.sizeBytes(); - } catch (IOException e) { - LOGGER.warn("Failed to inspect local file {} for backup {}", candidate, backup.id(), e); - return false; - } - } - - private void deletePlainDuplicate(Path downloadsDir, BackupDto backup) { - Path plainPath = downloadsDir.resolve(backup.fileName()); - Path autoPath = downloadsDir.resolve(withAutoSuffix(backup.fileName())); - - if (!Files.exists(autoPath) || !Files.exists(plainPath)) { - return; - } - - try { - long autoSize = Files.size(autoPath); - long plainSize = Files.size(plainPath); - if (autoSize == backup.sizeBytes() && plainSize == backup.sizeBytes()) { - Files.deleteIfExists(plainPath); - LOGGER.info("Auto pickup removed plain duplicate for backup {} and kept {}", backup.id(), autoPath.getFileName()); - } - } catch (IOException e) { - LOGGER.warn("Auto pickup failed to reconcile plain duplicate for backup {}", backup.id(), e); - } - } - - private PickupStartDto startPickupTask(String activeServer, BackupDto backup) { - Path downloadsDir = downloadsDirectory(); - Path existingPath = findExistingCopy(downloadsDir, backup); - if (existingPath != null) { - String taskId = UUID.randomUUID().toString(); - PickupTaskState existingState = new PickupTaskState(taskId, backup.id(), backup.fileName(), backup.sizeBytes()); - existingState.status = PickupStatus.COMPLETED; - existingState.bytesWritten = backup.sizeBytes(); - existingState.savedPath = existingPath; - pickupTasks.put(taskId, existingState); - LOGGER.info("Pickup task {} reused existing local copy for backup {} at {}", taskId, backup.id(), existingPath); - return new PickupStartDto(taskId, backup.id(), backup.fileName(), backup.sizeBytes()); - } - - Path destination = downloadsDir.resolve(backup.fileName()); - String taskId = UUID.randomUUID().toString(); - PickupTaskState state = new PickupTaskState(taskId, backup.id(), backup.fileName(), backup.sizeBytes()); - pickupTasks.put(taskId, state); - - LOGGER.info("Starting pickup task {} for backup {} to {}", taskId, backup.id(), destination); - pickupExecutor.submit(() -> runPickupTask(activeServer, backup, destination, state)); - - return new PickupStartDto(taskId, backup.id(), backup.fileName(), backup.sizeBytes()); - } - - private Path pickupManual(String activeServer, BackupDto backup) { - Path downloadsDir = downloadsDirectory(); - Path existingPath = findExistingCopy(downloadsDir, backup); - if (existingPath != null) { - LOGGER.info("Manual pickup: skipping {} because client already has a local copy at {}", backup.id(), existingPath); - return existingPath; - } - - Path destination = downloadsDir.resolve(backup.fileName()); - LOGGER.info("Manual pickup: downloading {} to {}", backup.fileName(), destination); - return serverApiService.downloadById(activeServer, backup.id(), destination); - } - - private void runPickupTask(String activeServer, BackupDto backup, Path destination, PickupTaskState state) { - state.status = PickupStatus.RUNNING; - try { - Path downloaded = serverApiService.downloadById( - activeServer, - backup.id(), - destination, - (bytesWritten, totalBytes) -> { - state.bytesWritten = bytesWritten; - if (totalBytes > 0) { - state.totalBytes = totalBytes; - } - } - ); - state.savedPath = downloaded; - if (state.totalBytes <= 0) { - state.totalBytes = state.bytesWritten; - } - state.status = PickupStatus.COMPLETED; - LOGGER.info("Pickup task {} completed: {}", state.taskId, downloaded); - } catch (RuntimeException ex) { - state.status = PickupStatus.FAILED; - state.error = ex.getMessage(); - LOGGER.warn("Pickup task {} failed for backup {}", state.taskId, backup.id(), ex); - } - } - - private BackupDto requireBackup(String activeServer, String backupId) { - return serverApiService.listBackups(activeServer).stream() - .filter(backup -> backup.id().equals(backupId)) - .findFirst() - .orElseThrow(() -> new IllegalStateException("Backup not found: " + backupId)); - } - - private String requireActiveServer() { - String activeServer = clientStateService.getActiveServer(); - if (activeServer == null || activeServer.isBlank()) { - LOGGER.error("Pickup requested but no active server is configured"); - throw new IllegalStateException("No active server selected"); - } - return activeServer; - } - - private BackupDto latestRequired(List backups) { - if (backups == null || backups.isEmpty()) { - throw new IllegalStateException("No backups found on server"); - } - return backups.get(0); - } - - private Path downloadsDirectory() { - return Path.of(configuration.getDownloadDirectory()).toAbsolutePath().normalize(); - } - - private String withAutoSuffix(String fileName) { - if (fileName.endsWith(".zip")) { - return fileName.substring(0, fileName.length() - 4) + AUTO_DOWNLOAD_SUFFIX + ".zip"; - } - return fileName + AUTO_DOWNLOAD_SUFFIX; - } - - @PreDestroy - public void shutdownPickupExecutor() { - pickupExecutor.shutdownNow(); - } - - public Duration updatePickupInterval(Duration interval) { - Duration updated = clientStateService.setPickupInterval(interval); - nextPickup = Instant.now().plus(updated); - return updated; - } -} diff --git a/src/main/java/wellatleastitried/mediaguardclient/service/ClientStateService.java b/src/main/java/wellatleastitried/mediaguardclient/service/ClientStateService.java deleted file mode 100644 index 9919fcd..0000000 --- a/src/main/java/wellatleastitried/mediaguardclient/service/ClientStateService.java +++ /dev/null @@ -1,133 +0,0 @@ -package wellatleastitried.mediagarrdclient.service; - -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.time.Duration; -import java.util.ArrayList; -import java.util.List; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Service; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.databind.ObjectMapper; - -import wellatleastitried.mediagarrdclient.Configuration; - -@Service -public class ClientStateService { - - private static final Logger LOGGER = LoggerFactory.getLogger(ClientStateService.class); - - @JsonIgnoreProperties(ignoreUnknown = true) - private static class ClientState { - public String activeServer = ""; - public long pickupIntervalSeconds = 43_200; - public List knownServers = new ArrayList<>(); - } - - private final Configuration configuration; - private final ObjectMapper mapper; - private final List knownServers = new ArrayList<>(); - private String activeServer; - private Duration pickupInterval; - - public ClientStateService(Configuration configuration, ObjectMapper mapper) { - this.configuration = configuration; - this.mapper = mapper; - this.pickupInterval = safe(configuration.getPickupInterval()); - this.activeServer = null; - load(); - LOGGER.info("ClientStateService initialized: activeServer={}, pickupInterval={}, knownServers={}", - activeServer, pickupInterval, knownServers); - } - - public synchronized String getActiveServer() { - return activeServer; - } - - public synchronized Duration getPickupInterval() { - return pickupInterval; - } - - public synchronized List getKnownServers() { - return List.copyOf(knownServers); - } - - public synchronized void updateKnownServers(List servers) { - knownServers.clear(); - knownServers.addAll(servers.stream().distinct().toList()); - if ((activeServer == null || activeServer.isBlank()) && !knownServers.isEmpty()) { - activeServer = knownServers.getFirst(); - LOGGER.info("Auto-selected first known server: {}", activeServer); - } - LOGGER.info("Known servers updated: {}", knownServers); - save(); - } - - public synchronized void setActiveServer(String serverUrl) { - LOGGER.info("Active server changed: {} -> {}", activeServer, serverUrl); - this.activeServer = serverUrl; - if (serverUrl != null && !serverUrl.isBlank() && !knownServers.contains(serverUrl)) { - knownServers.add(serverUrl); - } - save(); - } - - public synchronized Duration setPickupInterval(Duration interval) { - this.pickupInterval = safe(interval); - LOGGER.info("Pickup interval updated to: {}", this.pickupInterval); - save(); - return this.pickupInterval; - } - - private void load() { - Path path = statePath(); - if (!Files.exists(path)) { - LOGGER.info("No state file found at {}, starting fresh", path); - return; - } - try { - ClientState state = mapper.readValue(path.toFile(), ClientState.class); - activeServer = state.activeServer; - pickupInterval = Duration.ofSeconds(state.pickupIntervalSeconds); - knownServers.clear(); - knownServers.addAll(state.knownServers); - if ((activeServer == null || activeServer.isBlank()) && !knownServers.isEmpty()) { - activeServer = knownServers.getFirst(); - } - LOGGER.info("State loaded from {}: activeServer={}, pickupInterval={}, knownServers={}", - path, activeServer, pickupInterval, knownServers); - } catch (IOException e) { - LOGGER.warn("Failed to load state from {}, starting with defaults", path, e); - } - } - - private void save() { - Path path = statePath(); - try { - Files.createDirectories(path.getParent()); - ClientState state = new ClientState(); - state.activeServer = activeServer == null ? "" : activeServer; - state.pickupIntervalSeconds = pickupInterval.toSeconds(); - state.knownServers = List.copyOf(knownServers); - mapper.writerWithDefaultPrettyPrinter().writeValue(path.toFile(), state); - LOGGER.debug("Client state persisted to {}", path); - } catch (IOException e) { - throw new IllegalStateException("Failed to persist client state", e); - } - } - - private Path statePath() { - return Path.of(configuration.getStateFile()).toAbsolutePath().normalize(); - } - - private Duration safe(Duration duration) { - if (duration == null || duration.isNegative() || duration.isZero()) { - return Duration.ofHours(12); - } - return duration; - } -} diff --git a/src/main/java/wellatleastitried/mediaguardclient/service/ServerApiService.java b/src/main/java/wellatleastitried/mediaguardclient/service/ServerApiService.java deleted file mode 100644 index 1c4628d..0000000 --- a/src/main/java/wellatleastitried/mediaguardclient/service/ServerApiService.java +++ /dev/null @@ -1,192 +0,0 @@ -package wellatleastitried.mediagarrdclient.service; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.URI; -import java.net.http.HttpClient; -import java.net.http.HttpRequest; -import java.net.http.HttpResponse; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.StandardCopyOption; -import java.nio.file.StandardOpenOption; -import java.time.Duration; -import java.util.List; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.core.ParameterizedTypeReference; -import org.springframework.http.MediaType; -import org.springframework.http.client.JdkClientHttpRequestFactory; -import org.springframework.stereotype.Service; -import org.springframework.web.client.RestClient; - -import wellatleastitried.mediagarrdclient.api.Endpoints; -import wellatleastitried.mediagarrdclient.dto.BackupDto; -import wellatleastitried.mediagarrdclient.dto.ServerStatusDto; - -@Service -public class ServerApiService { - - @FunctionalInterface - public interface DownloadProgressListener { - void onProgress(long bytesWritten, long totalBytes); - } - - private static final Logger LOGGER = LoggerFactory.getLogger(ServerApiService.class); - - private final HttpClient httpClient = HttpClient.newBuilder() - .followRedirects(HttpClient.Redirect.ALWAYS) - .build(); - - private final RestClient restClient = RestClient.builder() - .requestFactory(new JdkClientHttpRequestFactory(httpClient)) - .build(); - - public ServerStatusDto health(String serverUrl) { - LOGGER.info("Probing server health: {}", serverUrl); - ServerStatusDto dto = restClient.get() - .uri(serverUrl + Endpoints.SERVER_HEALTH.getPath()) - .retrieve() - .body(ServerStatusDto.class); - LOGGER.info("Server health OK: {}, running={}, interval={}", serverUrl, - dto != null ? dto.running() : "?", dto != null ? dto.backupInterval() : "?"); - return dto; - } - - public List listBackups(String serverUrl) { - LOGGER.info("Fetching backup list from: {}", serverUrl); - List response = restClient.get() - .uri(serverUrl + Endpoints.SERVER_BACKUPS.getPath()) - .retrieve() - .body(new ParameterizedTypeReference<>() {}); - List result = response == null ? List.of() : response; - LOGGER.info("Received {} backup(s) from {}", result.size(), serverUrl); - return result; - } - - public void triggerBackup(String serverUrl) { - LOGGER.info("Triggering backup on: {}", serverUrl); - restClient.post() - .uri(serverUrl + Endpoints.SERVER_BACKUP_RUN.getPath()) - .retrieve() - .toBodilessEntity(); - LOGGER.info("Backup trigger acknowledged by: {}", serverUrl); - } - - public void updateServerSchedule(String serverUrl, Duration interval) { - LOGGER.info("Updating server schedule on {} to interval={}", serverUrl, interval); - restClient.put() - .uri(serverUrl + Endpoints.SERVER_SCHEDULE.getPath()) - .contentType(MediaType.APPLICATION_JSON) - .body("{\"backupInterval\":\"" + interval + "\"}") - .retrieve() - .toBodilessEntity(); - LOGGER.info("Server schedule update acknowledged by: {}", serverUrl); - } - - public Path downloadLatest(String serverUrl, Path destinationPath) { - return downloadLatest(serverUrl, destinationPath, null); - } - - public Path downloadLatest(String serverUrl, Path destinationPath, DownloadProgressListener progressListener) { - LOGGER.info("Downloading latest backup from {} to {}", serverUrl, destinationPath); - - return downloadFromUri( - URI.create(serverUrl + Endpoints.SERVER_BACKUP_LATEST_DOWNLOAD.getPath()), - destinationPath, - "latest backup", - progressListener - ); - } - - public Path downloadById(String serverUrl, String backupId, Path destinationPath) { - return downloadById(serverUrl, backupId, destinationPath, null); - } - - public Path downloadById(String serverUrl, String backupId, Path destinationPath, DownloadProgressListener progressListener) { - LOGGER.info("Downloading backup id={} from {} to {}", backupId, serverUrl, destinationPath); - - return downloadFromUri( - URI.create(serverUrl + Endpoints.SERVER_BACKUPS.getPath() + "/" + backupId + "/download"), - destinationPath, - "backup " + backupId, - progressListener - ); - } - - private Path downloadFromUri(URI uri, Path destinationPath, String operationName, DownloadProgressListener progressListener) { - HttpRequest request = HttpRequest.newBuilder(uri).GET().build(); - - try { - HttpResponse response = httpClient.send(request, HttpResponse.BodyHandlers.ofInputStream()); - int status = response.statusCode(); - if (status < 200 || status >= 300) { - String snippet; - try (InputStream errorBody = response.body()) { - snippet = new String(errorBody.readNBytes(256)); - } - LOGGER.error("{} download failed from {} with HTTP {}: {}", operationName, uri, status, snippet); - throw new IllegalStateException(operationName + " download failed with HTTP " + status); - } - - Files.createDirectories(destinationPath.getParent()); - Path tempPath = destinationPath.resolveSibling(destinationPath.getFileName().toString() + ".tmp"); - long totalBytes = response.headers().firstValueAsLong("Content-Length").orElse(-1L); - - try (InputStream inputStream = response.body(); - OutputStream outputStream = Files.newOutputStream( - tempPath, - StandardOpenOption.CREATE, - StandardOpenOption.TRUNCATE_EXISTING, - StandardOpenOption.WRITE - )) { - byte[] buffer = new byte[8192]; - long bytesWritten = 0L; - int read; - while ((read = inputStream.read(buffer)) != -1) { - outputStream.write(buffer, 0, read); - bytesWritten += read; - if (progressListener != null) { - progressListener.onProgress(bytesWritten, totalBytes); - } - } - } - - if (!looksLikeZip(tempPath)) { - long size = Files.size(tempPath); - Files.deleteIfExists(tempPath); - LOGGER.error("{} download returned non-zip payload from {} ({} bytes)", operationName, uri, size); - throw new IllegalStateException("Server returned non-zip content for " + operationName + " download"); - } - - Files.move(tempPath, destinationPath, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); - LOGGER.info("Download complete: {} ({} bytes)", destinationPath.getFileName(), Files.size(destinationPath)); - return destinationPath; - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - LOGGER.error("{} download interrupted for {}", operationName, uri, e); - throw new IllegalStateException(operationName + " download interrupted", e); - } catch (IOException e) { - LOGGER.error("Failed to persist {} download to {}", operationName, destinationPath, e); - throw new IllegalStateException("Failed to persist " + operationName + " download", e); - } - } - - private boolean looksLikeZip(Path path) throws IOException { - byte[] header = new byte[4]; - try (InputStream in = Files.newInputStream(path, StandardOpenOption.READ)) { - int read = in.read(header); - if (read < 4) { - return false; - } - } - - return header[0] == 'P' - && header[1] == 'K' - && ((header[2] == 3 && header[3] == 4) - || (header[2] == 5 && header[3] == 6) - || (header[2] == 7 && header[3] == 8)); - } -} diff --git a/src/main/java/wellatleastitried/mediaguardclient/service/ServerDiscoveryService.java b/src/main/java/wellatleastitried/mediaguardclient/service/ServerDiscoveryService.java deleted file mode 100644 index 5de7b05..0000000 --- a/src/main/java/wellatleastitried/mediaguardclient/service/ServerDiscoveryService.java +++ /dev/null @@ -1,293 +0,0 @@ -package wellatleastitried.mediagarrdclient.service; - -import java.net.Inet4Address; -import java.net.InetAddress; -import java.net.URI; -import java.net.NetworkInterface; -import java.net.SocketException; -import java.net.http.HttpClient; -import java.time.Duration; -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.List; -import java.util.Optional; -import java.util.Set; -import java.util.concurrent.CompletionService; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.ExecutorCompletionService; -import java.util.concurrent.Executors; -import java.util.concurrent.atomic.AtomicBoolean; - -import org.springframework.http.HttpStatusCode; -import org.springframework.http.client.JdkClientHttpRequestFactory; -import org.springframework.stereotype.Service; -import org.springframework.web.client.RestClient; -import org.springframework.web.client.RestClientException; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import wellatleastitried.mediagarrdclient.Configuration; - -@Service -public class ServerDiscoveryService { - - private static final Logger LOGGER = LoggerFactory.getLogger(ServerDiscoveryService.class); - - private static final int MIN_NON_STANDARD_PORT = 1024; - private static final int MAX_PORT = 65535; - private static final int PORT_SCAN_THREADS = 128; - private static final int DISCOVERY_THREADS = 64; - - private final Configuration configuration; - private final RestClient restClient; - - public ServerDiscoveryService(Configuration configuration) { - this.configuration = configuration; - HttpClient httpClient = HttpClient.newBuilder() - .followRedirects(HttpClient.Redirect.NORMAL) - .connectTimeout(Duration.ofMillis(2500)) - .build(); - JdkClientHttpRequestFactory requestFactory = new JdkClientHttpRequestFactory(httpClient); - requestFactory.setReadTimeout(Duration.ofMillis(3000)); - this.restClient = RestClient.builder().requestFactory(requestFactory).build(); - } - - public List discover() { - List prefixes = localPrefixes(); - Set discovered = new java.util.LinkedHashSet<>(); - - LOGGER.info("Starting network discovery: localPrefixes={}", prefixes); - - String preferredServerIp = configuration.getPreferredServerIp(); - if (preferredServerIp != null && !preferredServerIp.isBlank()) { - LOGGER.info("Probing preferred server IP: {}", preferredServerIp); - resolveServerByIp(preferredServerIp).ifPresent(url -> { - LOGGER.info("Preferred IP resolved: {}", url); - discovered.add(url); - }); - } - - if (prefixes.isEmpty()) { - LOGGER.warn("No local network prefixes detected, skipping subnet scan"); - return discovered.stream().toList(); - } - - List portsToProbe = discoveryPorts(); - LOGGER.info("Scanning {} subnet prefix(es) with {} port(s) each, ports={}", prefixes.size(), portsToProbe.size(), portsToProbe); - Set candidates = new java.util.LinkedHashSet<>(); - for (String prefix : prefixes) { - for (int host = 1; host <= 254; host++) { - String ip = prefix + "." + host; - for (Integer port : portsToProbe) { - candidates.add("http://" + ip + ":" + port); - } - } - } - - ExecutorService executor = Executors.newFixedThreadPool(DISCOVERY_THREADS); - LOGGER.info("Probing {} candidate endpoints with {} threads", candidates.size(), DISCOVERY_THREADS); - try { - CompletionService completionService = new ExecutorCompletionService<>(executor); - int submitted = 0; - for (String candidate : candidates) { - completionService.submit(() -> isHealthy(candidate) ? candidate : null); - submitted++; - } - - for (int i = 0; i < submitted; i++) { - try { - String healthy = completionService.take().get(); - if (healthy != null) { - LOGGER.info("Discovered server: {}", healthy); - discovered.add(healthy); - } - } catch (InterruptedException ex) { - Thread.currentThread().interrupt(); - break; - } catch (ExecutionException ignored) { - } - } - } finally { - executor.shutdownNow(); - } - - LOGGER.info("Network discovery complete, found {} server(s): {}", discovered.size(), discovered); - return discovered.stream().toList(); - } - - private List discoveryPorts() { - Set ports = new java.util.LinkedHashSet<>(); - ports.add(configuration.getServerPort()); - ports.add(38471); - ports.add(8080); - ports.add(3000); - ports.add(5000); - ports.add(8081); - ports.add(80); - ports.add(443); - return new ArrayList<>(ports); - } - - public Optional resolveServerByIp(String input) { - return resolveServerByIp(input, null); - } - - public Optional resolveServerByIp(String input, Integer preferredPort) { - String host = normalizeHost(input); - if (host == null) { - LOGGER.warn("resolveServerByIp: invalid input '{}'", input); - return Optional.empty(); - } - - LOGGER.info("Resolving server at host={}, preferredPort={}", host, preferredPort); - - if (preferredPort != null) { - String preferredCandidate = toUrl(host, preferredPort); - LOGGER.debug("Probing preferred port: {}", preferredCandidate); - if (isHealthy(preferredCandidate)) { - LOGGER.info("Server found at preferred port: {}", preferredCandidate); - return Optional.of(preferredCandidate); - } - LOGGER.debug("Preferred port {} not responding", preferredPort); - } - - int defaultPort = configuration.getServerPort(); - String defaultCandidate = toUrl(host, defaultPort); - LOGGER.debug("Probing default port: {}", defaultCandidate); - if (isHealthy(defaultCandidate)) { - LOGGER.info("Server found at default port: {}", defaultCandidate); - return Optional.of(defaultCandidate); - } - - LOGGER.debug("Default port {} not responding, trying common ports", defaultPort); - for (Integer quickPort : discoveryPorts()) { - if (quickPort == defaultPort) { - continue; - } - if (preferredPort != null && quickPort.equals(preferredPort)) { - continue; - } - String quickCandidate = toUrl(host, quickPort); - LOGGER.debug("Probing common port: {}", quickCandidate); - if (isHealthy(quickCandidate)) { - LOGGER.info("Server found at common port: {}", quickCandidate); - return Optional.of(quickCandidate); - } - } - - LOGGER.info("Common ports exhausted for {}, starting full port scan ({}-{})", host, MIN_NON_STANDARD_PORT, MAX_PORT); - ExecutorService executor = Executors.newFixedThreadPool(PORT_SCAN_THREADS); - AtomicBoolean stop = new AtomicBoolean(false); - try { - CompletionService completionService = new ExecutorCompletionService<>(executor); - int submitted = 0; - for (int port = MIN_NON_STANDARD_PORT; port <= MAX_PORT; port++) { - if (port == defaultPort) { - continue; - } - if (preferredPort != null && port == preferredPort) { - continue; - } - - final int candidatePort = port; - completionService.submit(() -> { - if (stop.get()) { - return null; - } - String candidate = toUrl(host, candidatePort); - if (isHealthy(candidate)) { - stop.set(true); - return candidate; - } - return null; - }); - submitted++; - } - - for (int i = 0; i < submitted; i++) { - String candidate = completionService.take().get(); - if (candidate != null) { - LOGGER.info("Server found via full port scan: {}", candidate); - return Optional.of(candidate); - } - } - LOGGER.warn("Full port scan exhausted for {}, no server found", host); - return Optional.empty(); - } catch (InterruptedException ex) { - Thread.currentThread().interrupt(); - LOGGER.warn("Port scan interrupted for {}", host); - return Optional.empty(); - } catch (ExecutionException ex) { - LOGGER.warn("Port scan execution error for {}: {}", host, ex.getMessage()); - return Optional.empty(); - } finally { - executor.shutdownNow(); - } - } - - private List localPrefixes() { - List prefixes = new ArrayList<>(); - try { - Enumeration interfaces = NetworkInterface.getNetworkInterfaces(); - while (interfaces.hasMoreElements()) { - NetworkInterface networkInterface = interfaces.nextElement(); - if (!networkInterface.isUp() || networkInterface.isLoopback()) { - continue; - } - Enumeration addresses = networkInterface.getInetAddresses(); - while (addresses.hasMoreElements()) { - InetAddress address = addresses.nextElement(); - if (address instanceof Inet4Address ipv4 && !ipv4.isLoopbackAddress()) { - byte[] bytes = ipv4.getAddress(); - prefixes.add((bytes[0] & 0xFF) + "." + (bytes[1] & 0xFF) + "." + (bytes[2] & 0xFF)); - } - } - } - } catch (SocketException ignored) { - } - return prefixes.stream().distinct().toList(); - } - - private boolean isHealthy(String candidate) { - try { - HttpStatusCode status = restClient.get() - .uri(candidate + "/api/v1/health") - .retrieve() - .toBodilessEntity() - .getStatusCode(); - boolean ok = status.is2xxSuccessful(); - if (ok) { - LOGGER.debug("Health check OK: {}", candidate); - } - return ok; - } catch (RestClientException ex) { - LOGGER.debug("Health check failed for {}: {}", candidate, ex.getMessage()); - return false; - } - } - - private String normalizeHost(String input) { - if (input == null) { - return null; - } - String trimmed = input.trim(); - if (trimmed.isBlank()) { - return null; - } - - try { - URI uri = trimmed.contains("://") ? URI.create(trimmed) : URI.create("http://" + trimmed); - if (uri.getHost() != null && !uri.getHost().isBlank()) { - return uri.getHost(); - } - } catch (IllegalArgumentException ignored) { - } - return trimmed; - } - - private String toUrl(String host, int port) { - return "http://" + host + ":" + port; - } -} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index fdda830..3a82616 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -1,10 +1,16 @@ server: port: ${CLIENT_PORT:8081} +spring: + web: + resources: + cache: + period: 0 + mediagarrd: client: - state-file: ${CLIENT_STATE_FILE:./data/client/state.json} - download-directory: ${CLIENT_DOWNLOAD_DIRECTORY:./data/client/downloads} + state-file: ${CLIENT_STATE_FILE:/var/lib/mediagarrd/client/state.json} + download-directory: ${CLIENT_DOWNLOAD_DIRECTORY:/var/lib/mediagarrd/downloads} pickup-interval: ${CLIENT_PICKUP_INTERVAL:PT12H} - server-port: ${MEDIAGARRD_SERVER_PORT:8080} + server-port: ${MEDIAGARRD_SERVER_PORT:38471} preferred-server-ip: ${MEDIAGARRD_SERVER_IP:} diff --git a/src/main/resources/static/css/mediagarrd.css b/src/main/resources/static/css/mediagarrd.css new file mode 100644 index 0000000..b749ca2 --- /dev/null +++ b/src/main/resources/static/css/mediagarrd.css @@ -0,0 +1,305 @@ +:root { + --bg: #000; + --surface: #0a0a0a; + --surface-raised: #111; + --ink: #f5f5f5; + --muted: #737373; + --subtle: #404040; + --border: #1f1f1f; + --border-mid: #2e2e2e; + --accent: #f5f5f5; + --accent-dim: #d4d4d4; + --ok: #22c55e; + --warn: #ef4444; + --mono: "JetBrains Mono", "Fira Code", ui-monospace, monospace; +} + +*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; } + +body { + font-family: "Space Grotesk", "Inter", "Avenir Next", ui-sans-serif, system-ui, sans-serif; + background: var(--bg); + color: var(--ink); + min-height: 100vh; + font-size: 14px; + line-height: 1.5; +} + +[hidden] { display: none !important; } + +.topbar { + display: flex; + align-items: center; + justify-content: space-between; + gap: 1rem; + flex-wrap: wrap; + padding: 0.85rem 1.5rem; + border-bottom: 1px solid var(--border); + background: var(--surface); + position: sticky; + top: 0; + z-index: 10; +} + +.brand { display: flex; flex-direction: column; } +.brand-title { font-size: 1rem; font-weight: 700; letter-spacing: 0.1em; text-transform: uppercase; } +.brand-sub { font-size: 0.72rem; color: var(--muted); letter-spacing: 0.05em; } + +.view-toggle { display: flex; border: 1px solid var(--border-mid); } +.view-toggle button { background: transparent; color: var(--muted); border: none; padding: 0.4rem 0.85rem; } +.view-toggle button:hover { background: var(--surface-raised); color: var(--ink); } +.view-toggle button[aria-pressed="true"] { background: var(--accent); color: #000; } + +.conn-badge { + display: flex; + align-items: center; + gap: 0.45rem; + padding: 0.32rem 0.75rem; + border: 1px solid var(--border-mid); + font-size: 0.75rem; + font-weight: 600; + text-transform: uppercase; + letter-spacing: 0.06em; + color: var(--muted); + background: var(--surface-raised); + white-space: nowrap; +} +.conn-badge .dot { + width: 7px; + height: 7px; + border-radius: 50%; + background: var(--subtle); + flex-shrink: 0; + transition: background 300ms; +} +.conn-badge.ok { color: #a3e8bc; border-color: #1e3b2a; } +.conn-badge.ok .dot { background: var(--ok); box-shadow: 0 0 6px var(--ok); } +.conn-badge.down { color: #fca5a5; border-color: #3b1111; } +.conn-badge.down .dot { background: var(--warn); box-shadow: 0 0 6px var(--warn); } +.conn-badge.checking { color: var(--accent-dim); } +.conn-badge.checking .dot { background: #a3a3a3; } + +.page { max-width: 1200px; margin: 0 auto; padding: 1.5rem; animation: fadein 350ms ease; } +.workspace { + display: grid; + grid-template-columns: 360px 1fr; + gap: 1rem; + align-items: start; +} +@media (max-width: 900px) { .workspace { grid-template-columns: 1fr; } } + +.panel { background: var(--surface); border: 1px solid var(--border); } +.panel.wide { grid-column: 1 / -1; } +.stack { display: flex; flex-direction: column; gap: 1rem; } +.panel-header { + display: flex; + align-items: center; + justify-content: space-between; + padding: 0.7rem 1rem; + border-bottom: 1px solid var(--border); +} +.panel-title { font-size: 0.72rem; font-weight: 700; letter-spacing: 0.1em; text-transform: uppercase; color: var(--accent-dim); } +.panel-body { padding: 1rem; } +.panel-body + .panel-body { border-top: 1px solid var(--border); } +.section-label { + font-size: 0.68rem; + font-weight: 600; + letter-spacing: 0.08em; + text-transform: uppercase; + color: var(--muted); + margin-bottom: 0.6rem; +} + +.field-group { display: flex; flex-direction: column; gap: 0.4rem; margin-bottom: 0.75rem; } +.field-label { font-size: 0.7rem; color: var(--muted); letter-spacing: 0.04em; } +.note { font-size: 0.72rem; color: var(--muted); margin-top: 0.45rem; } +.input-row { display: grid; grid-template-columns: 1fr auto; gap: 0.5rem; } +.input-row-2 { display: grid; grid-template-columns: 1fr 110px; gap: 0.5rem; } +.button-row { display: flex; gap: 0.5rem; flex-wrap: wrap; } +.button-row > button { flex: 1; } + +input, select { + width: 100%; + background: var(--bg); + color: var(--ink); + border: 1px solid var(--border-mid); + padding: 0.5rem 0.65rem; + font: inherit; + font-size: 0.85rem; + outline: none; + transition: border-color 150ms; +} +input:focus, select:focus { border-color: var(--subtle); } +input::placeholder { color: var(--muted); } + +button { + background: var(--accent); + color: #000; + border: 1px solid var(--accent); + padding: 0.5rem 0.85rem; + font: inherit; + font-size: 0.78rem; + font-weight: 700; + letter-spacing: 0.05em; + text-transform: uppercase; + cursor: pointer; + white-space: nowrap; + transition: background 120ms, color 120ms, border-color 120ms, transform 70ms, box-shadow 120ms; +} +button:hover { background: var(--accent-dim); border-color: var(--accent-dim); } +button:active, button.clicked { transform: translateY(1px) scale(0.98); box-shadow: inset 0 0 0 2px #000; } +button:disabled { cursor: not-allowed; opacity: 0.62; transform: none; } +button.ghost { background: transparent; color: var(--ink); border-color: var(--border-mid); } +button.ghost:hover { border-color: var(--subtle); background: var(--surface-raised); } +button.danger { background: transparent; color: #fca5a5; border-color: #3b1111; } +button.danger:hover { background: #1c0606; } +button.full { width: 100%; } +button.small { padding: 0.3rem 0.65rem; font-size: 0.7rem; } + +.action-btn { position: relative; overflow: hidden; } +.action-btn .btn-label { position: relative; z-index: 1; } +.btn-progress { + position: absolute; + left: 0; + right: 0; + bottom: 0; + height: 2px; + display: none; + background: rgba(255, 255, 255, 0.12); + overflow: hidden; +} +.action-btn.busy .btn-progress { display: block; } +.btn-progress.indeterminate::after { + content: ''; + display: block; + width: 34%; + height: 100%; + background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.85), transparent); + animation: sweep 1.1s linear infinite; +} +.btn-progress-fill { + display: block; + width: 0; + height: 100%; + background: linear-gradient(90deg, #9ca3af, #f5f5f5); + transition: width 120ms linear; +} + +.stat-row { + display: flex; + align-items: baseline; + justify-content: space-between; + padding: 0.35rem 0; + border-bottom: 1px solid var(--border); + font-size: 0.83rem; +} +.stat-row:last-child { border-bottom: none; } +.stat-key { color: var(--muted); font-size: 0.75rem; letter-spacing: 0.03em; } +.stat-val { font-weight: 600; text-align: right; font-variant-numeric: tabular-nums; } + +.tag { + display: inline-block; + padding: 0.12rem 0.45rem; + font-size: 0.7rem; + font-weight: 700; + letter-spacing: 0.07em; + text-transform: uppercase; + border: 1px solid var(--border-mid); + color: var(--muted); +} +.tag.running { color: #a3e8bc; border-color: #1e3b2a; } + +.scan-bar { display: none; height: 2px; background: var(--border); overflow: hidden; margin-top: 0.6rem; } +.scan-bar.active { display: block; } +.scan-bar > span { + display: block; + width: 30%; + height: 100%; + background: linear-gradient(90deg, transparent, var(--accent-dim), transparent); + animation: sweep 1.1s linear infinite; +} + +.server-url { + font-family: var(--mono); + font-size: 0.78rem; + color: var(--accent-dim); + word-break: break-all; + padding: 0.4rem 0.6rem; + background: var(--surface-raised); + border: 1px solid var(--border); + margin-bottom: 0.75rem; +} + +table { width: 100%; border-collapse: collapse; font-size: 0.82rem; } +thead th { + padding: 0.5rem 0.75rem; + text-align: left; + font-size: 0.68rem; + font-weight: 700; + letter-spacing: 0.08em; + text-transform: uppercase; + color: var(--muted); + border-bottom: 1px solid var(--border-mid); +} +thead th.sortable { cursor: pointer; user-select: none; transition: color 120ms; white-space: nowrap; } +thead th.sortable:hover, thead th.sortable.active { color: var(--accent-dim); } +.sort-indicator { margin-left: 0.25rem; font-size: 0.65rem; color: var(--subtle); vertical-align: middle; } +thead th.sortable.active .sort-indicator { color: var(--accent-dim); } +tbody tr { border-bottom: 1px solid var(--border); transition: background 100ms; } +tbody tr:last-child { border-bottom: none; } +tbody tr:hover { background: var(--surface-raised); } +tbody td { padding: 0.55rem 0.75rem; vertical-align: middle; } +.td-mono { font-family: var(--mono); font-size: 0.78rem; color: var(--accent-dim); white-space: pre-line; word-break: break-all; } +.td-muted { color: var(--muted); } +.td-id { font-size: 0.7rem; } +.actions-cell { text-align: right; white-space: nowrap; } +.actions-cell button + button { margin-left: 0.4rem; } +.empty-state { padding: 2.5rem 1rem; text-align: center; color: var(--muted); font-size: 0.83rem; } + +.icon-btn { + min-width: 34px; + height: 28px; + padding: 0; + font-size: 0.95rem; + line-height: 1; + font-weight: 800; + letter-spacing: 0; + text-transform: none; +} +.row-progress-circle { + width: 16px; + height: 16px; + border-radius: 50%; + display: inline-block; + position: relative; + background: conic-gradient(var(--accent-dim) var(--p, 0%), var(--border-mid) 0); +} +.row-progress-circle::after { + content: ''; + position: absolute; + inset: 3px; + border-radius: 50%; + background: var(--surface); +} + +.banner { + display: none; + margin-bottom: 1rem; + padding: 0.65rem 1rem; + font-size: 0.82rem; + background: #1c0606; + border: 1px solid #3b1111; + color: #fca5a5; +} +.banner.visible { display: block; } +.banner.ok { background: #06140b; border-color: #1e3b2a; color: #a3e8bc; } + +@keyframes sweep { + from { transform: translateX(-150%); } + to { transform: translateX(420%); } +} + +@keyframes fadein { + from { opacity: 0; transform: translateY(6px); } + to { opacity: 1; transform: translateY(0); } +} diff --git a/src/main/resources/static/index.html b/src/main/resources/static/index.html index f15c498..73c4516 100644 --- a/src/main/resources/static/index.html +++ b/src/main/resources/static/index.html @@ -4,1198 +4,207 @@ MediaGarrd Client - + + - -
MediaGarrd Client Dashboard
+
- Connecting... + Connecting...
-
+
+ - -
-
- Server Connection -
+
+
+
Server Connection
- -
- -
-
- - +
+ +
+
+ + +
-
- -
+ + - -
- -
- +
+ +
+ +
+
- -
- - -
- - - -

Last scan: not run yet.

-
-
- - -
-
- Server Status -
- -
-
No server connected.
-
+ +
+
Server Status
+ +
+

No server connected.

+
-
- -
- -
- - +
+ +
+ + +
-
- -
- -
- - -
-
- - +
+ +
+ + +
+ +
+ + +
+
+ Backup Archives +
-
- - - -
- - -
-
- Backup Archives - -
- - +
+ + + + + + + + + + +
File Size Created ID Get
+

No backups loaded. Connect to a server to view archives.

+ + +
+
+ +
+ + + +
+ diff --git a/src/main/resources/static/js/api.js b/src/main/resources/static/js/api.js new file mode 100644 index 0000000..7e636d3 --- /dev/null +++ b/src/main/resources/static/js/api.js @@ -0,0 +1,34 @@ +async function request(method, url, body) { + const response = await fetch(url, { + method, + headers: body === undefined ? {} : { 'Content-Type': 'application/json' }, + body: body === undefined ? undefined : JSON.stringify(body), + }); + if (!response.ok) { + const data = await response.json().catch(() => ({})); + throw new Error(data.error || data.message || `${method} ${url} failed (${response.status})`); + } + const text = await response.text(); + return text ? JSON.parse(text) : null; +} + +const encode = encodeURIComponent; + +export const api = { + status: () => request('GET', '/api/client/status'), + discover: () => request('POST', '/api/client/discover'), + serverHealth: () => request('GET', '/api/client/server-health'), + selectServer: (selection) => request('PUT', '/api/client/server', selection), + listBackups: () => request('GET', '/api/client/backups'), + runBackup: () => request('POST', '/api/client/backups/run'), + pickupLatest: () => request('POST', '/api/client/pickup'), + pickupById: (id) => request('POST', `/api/client/pickup/${encode(id)}`), + pickupProgress: (taskId) => request('GET', `/api/client/pickup/progress/${encode(taskId)}`), + updatePickupInterval: (interval) => request('PUT', '/api/client/pickup-interval', { interval }), + serverConfig: () => request('GET', '/api/client/server-config'), + updateServerConfig: (config) => request('PUT', '/api/client/server-config', config), + listServices: () => request('GET', '/api/client/services'), + addService: (service) => request('POST', '/api/client/services', service), + updateService: (name, service) => request('PUT', `/api/client/services/${encode(name)}`, service), + removeService: (name) => request('DELETE', `/api/client/services/${encode(name)}`), +}; diff --git a/src/main/resources/static/js/backups.js b/src/main/resources/static/js/backups.js new file mode 100644 index 0000000..4d9aba4 --- /dev/null +++ b/src/main/resources/static/js/backups.js @@ -0,0 +1,206 @@ +import { api } from './api.js'; +import { bytes, percent, relativeTime } from './format.js'; + +const POLL_INTERVAL_MS = 350; + +export function initBackups({ root, actions }, notify, { refreshHealth }) { + const rows = root.querySelector('tbody'); + const empty = root.querySelector('[data-empty]'); + const headers = root.querySelectorAll('th[data-sort-key]'); + const template = root.querySelector('#backupTemplate'); + const runButton = actions.querySelector('[data-run]'); + const pickupButton = actions.querySelector('[data-pickup]'); + const sort = { key: 'fileName', dir: 'asc' }; + const rowTasks = new Map(); + const rowButtons = new Map(); + let backups = []; + let serverRunning = false; + let runInFlight = false; + let latestTask = null; + let pollTimer = null; + + function renderActions() { + const backupBusy = serverRunning || runInFlight; + runButton.disabled = backupBusy; + runButton.classList.toggle('busy', backupBusy); + runButton.querySelector('.btn-label').textContent = backupBusy ? 'Backup In Progress' : 'Run Backup Now'; + + pickupButton.disabled = Boolean(latestTask); + pickupButton.classList.toggle('busy', Boolean(latestTask)); + pickupButton.querySelector('.btn-label').textContent = latestTask ? 'Downloading...' : 'Download Latest'; + pickupButton.querySelector('.btn-progress-fill').style.width = + `${latestTask ? percent(latestTask.bytesWritten, latestTask.totalBytes) : 0}%`; + } + + function renderRowButton(id) { + const button = rowButtons.get(id); + if (!button) return; + const task = rowTasks.get(id); + button.disabled = Boolean(task); + if (!task) { + button.textContent = '↓'; + return; + } + const progress = document.createElement('span'); + progress.className = 'row-progress-circle'; + progress.style.setProperty('--p', `${percent(task.bytesWritten, task.totalBytes)}%`); + button.replaceChildren(progress); + } + + function compare(a, b) { + const dir = sort.dir === 'asc' ? 1 : -1; + if (sort.key === 'sizeBytes') return ((a.sizeBytes ?? 0) - (b.sizeBytes ?? 0)) * dir; + if (sort.key === 'createdAt') return (new Date(a.createdAt) - new Date(b.createdAt)) * dir; + return String(a[sort.key] ?? '').localeCompare(String(b[sort.key] ?? ''), undefined, { sensitivity: 'base' }) * dir; + } + + function renderRow(backup) { + const row = template.content.firstElementChild.cloneNode(true); + row.querySelector('[data-file]').textContent = backup.fileName; + row.querySelector('[data-size]').textContent = bytes(backup.sizeBytes); + row.querySelector('[data-created]').textContent = relativeTime(backup.createdAt); + const id = row.querySelector('[data-id]'); + id.textContent = backup.id.length > 22 ? `${backup.id.slice(0, 22)}…` : backup.id; + id.title = backup.id; + const button = row.querySelector('button'); + button.addEventListener('click', () => pickupById(backup.id)); + rowButtons.set(backup.id, button); + renderRowButton(backup.id); + return row; + } + + function renderTable(emptyMessage = 'No backup archives found on server.') { + headers.forEach((header) => { + const active = header.dataset.sortKey === sort.key; + header.classList.toggle('active', active); + header.querySelector('.sort-indicator').textContent = active ? (sort.dir === 'asc' ? '▲' : '▼') : '↕'; + }); + rowButtons.clear(); + rows.replaceChildren(...[...backups].sort(compare).map(renderRow)); + empty.textContent = emptyMessage; + empty.hidden = backups.length > 0; + } + + async function refresh() { + try { + backups = await api.listBackups() || []; + renderTable(); + } catch (error) { + backups = []; + renderTable(`${error.message}. Connect to a server to view archives.`); + } + } + + function finish(id) { + if (id === null) { + latestTask = null; + renderActions(); + refresh(); + } else { + rowTasks.delete(id); + renderRowButton(id); + } + } + + async function poll() { + const tasks = [...rowTasks].map(([id, task]) => ({ id, task })); + if (latestTask?.taskId) tasks.push({ id: null, task: latestTask }); + if (!tasks.length) { + pollTimer = null; + return; + } + await Promise.all(tasks.map(async ({ id, task }) => { + try { + const progress = await api.pickupProgress(task.taskId); + task.bytesWritten = progress.bytesWritten || 0; + task.totalBytes = progress.totalBytes || task.totalBytes; + if (progress.status === 'FAILED') notify.error(progress.error || 'Download failed'); + if (progress.status === 'COMPLETED' || progress.status === 'FAILED') finish(id); + } catch (error) { + notify.error(error); + finish(id); + } + })); + rowTasks.forEach((_, id) => renderRowButton(id)); + renderActions(); + pollTimer = setTimeout(poll, POLL_INTERVAL_MS); + } + + function startPolling() { + if (!pollTimer) pollTimer = setTimeout(poll, POLL_INTERVAL_MS); + } + + const toTask = (started) => ({ taskId: started.taskId, bytesWritten: 0, totalBytes: started.totalBytes || 0 }); + + async function pickupById(id) { + if (rowTasks.has(id)) return; + notify.clear(); + try { + rowTasks.set(id, toTask(await api.pickupById(id))); + renderRowButton(id); + startPolling(); + } catch (error) { + notify.error(error); + } + } + + pickupButton.addEventListener('click', async () => { + if (latestTask) return; + notify.clear(); + latestTask = { taskId: null, bytesWritten: 0, totalBytes: 0 }; + renderActions(); + try { + latestTask = toTask(await api.pickupLatest()); + startPolling(); + } catch (error) { + latestTask = null; + notify.error(error); + } + renderActions(); + }); + + runButton.addEventListener('click', async () => { + if (serverRunning || runInFlight) return; + notify.clear(); + runInFlight = true; + renderActions(); + try { + await api.runBackup(); + await refresh(); + } catch (error) { + notify.error(error); + } finally { + runInFlight = false; + await refreshHealth(); + } + }); + + headers.forEach((header) => header.addEventListener('click', () => { + const key = header.dataset.sortKey; + if (sort.key === key) { + sort.dir = sort.dir === 'asc' ? 'desc' : 'asc'; + } else { + sort.key = key; + sort.dir = key === 'createdAt' ? 'desc' : 'asc'; + } + renderTable(); + })); + + root.querySelector('[data-refresh]').addEventListener('click', () => { + notify.clear(); + refresh(); + }); + + renderTable('No backups loaded. Connect to a server to view archives.'); + renderActions(); + + return { + refresh, + setServerRunning(running) { + const finished = serverRunning && !running; + serverRunning = running; + renderActions(); + if (finished) refresh(); + }, + }; +} diff --git a/src/main/resources/static/js/connection.js b/src/main/resources/static/js/connection.js new file mode 100644 index 0000000..a081ce6 --- /dev/null +++ b/src/main/resources/static/js/connection.js @@ -0,0 +1,115 @@ +import { api } from './api.js'; +import { formatInterval } from './format.js'; + +export function initConnection({ root, statusPanel, badge }, notify, { onServerChanged, onHealth, onStatus }) { + const ipForm = root.querySelector('[data-ip-form]'); + const known = root.querySelector('[data-known]'); + const controls = root.querySelectorAll('button, input, select'); + const scanBar = root.querySelector('[data-scan-bar]'); + const scanNote = root.querySelector('[data-scan-note]'); + const details = statusPanel.querySelector('[data-details]'); + const noServer = statusPanel.querySelector('[data-no-server]'); + const state = statusPanel.querySelector('[data-state]'); + let busy = false; + let connected = null; + let healthRequest = null; + + function setBadge(kind, label) { + badge.className = `conn-badge ${kind}`; + badge.querySelector('[data-label]').textContent = label; + } + + function renderHealth(health) { + details.hidden = !health.connected; + noServer.hidden = health.connected; + if (!health.connected) { + noServer.textContent = health.activeServer ? `${health.activeServer} is not responding.` : 'No server connected.'; + if (!busy) setBadge(health.activeServer ? 'down' : '', health.activeServer ? 'Unreachable' : 'Not Connected'); + return; + } + const server = health.serverStatus; + statusPanel.querySelector('[data-url]').textContent = health.activeServer; + statusPanel.querySelector('[data-interval]').textContent = server ? formatInterval(server.backupInterval) : '—'; + statusPanel.querySelector('[data-retention]').textContent = server ? `${server.backupRetentionCount} archives` : '—'; + state.textContent = server?.running ? 'Running' : 'Idle'; + state.classList.toggle('running', Boolean(server?.running)); + if (!busy) setBadge('ok', health.activeServer.replace(/^https?:\/\//, '')); + } + + function refreshHealth() { + healthRequest ??= api.serverHealth() + .catch(() => ({ connected: false })) + .then((health) => { + const reconnected = health.connected && connected === false; + connected = health.connected; + renderHealth(health); + onHealth(health); + if (reconnected) onServerChanged(); + }) + .finally(() => { healthRequest = null; }); + return healthRequest; + } + + function renderKnown(status) { + const servers = status.knownServers || []; + const options = servers.map((server) => new Option(server, server, false, server === status.activeServer)); + known.replaceChildren(...(options.length ? options : [new Option('— none discovered yet —', '')])); + } + + async function refreshStatus() { + const status = await api.status(); + renderKnown(status); + onStatus(status); + await healthRequest; + await refreshHealth(); + } + + async function connect(label, action) { + if (busy) return null; + notify.clear(); + busy = true; + setBadge('checking', label); + scanBar.classList.add('active'); + controls.forEach((control) => { control.disabled = true; }); + let result = null; + try { + result = await action(); + } catch (error) { + notify.error(error); + } + busy = false; + scanBar.classList.remove('active'); + controls.forEach((control) => { control.disabled = false; }); + connected = null; + await refreshStatus().catch(notify.error); + if (result) onServerChanged(); + return result; + } + + ipForm.addEventListener('submit', (event) => { + event.preventDefault(); + const { ip, port } = ipForm.elements; + connect('Probing…', () => api.selectServer({ + serverIp: ip.value.trim(), + serverPort: port.value ? Number(port.value) : null, + })); + }); + + root.querySelector('[data-connect-known]').addEventListener('click', () => { + if (!known.value) { + notify.error('No server selected.'); + return; + } + connect('Connecting…', () => api.selectServer({ serverUrl: known.value })); + }); + + root.querySelector('[data-discover]').addEventListener('click', async () => { + if (busy) return; + scanNote.textContent = 'Scan in progress…'; + const found = await connect('Scanning…', api.discover); + const count = found?.length ?? 0; + scanNote.textContent = found ? `Last scan: found ${count} server${count === 1 ? '' : 's'}.` : 'Last scan: failed.'; + }); + + return { refreshStatus, refreshHealth }; +} diff --git a/src/main/resources/static/js/format.js b/src/main/resources/static/js/format.js new file mode 100644 index 0000000..68a82b6 --- /dev/null +++ b/src/main/resources/static/js/format.js @@ -0,0 +1,44 @@ +const ISO_DURATION = /^PT(?:(\d+(?:\.\d+)?)H)?(?:(\d+(?:\.\d+)?)M)?(?:(\d+(?:\.\d+)?)S)?$/i; + +export function seconds(duration) { + if (typeof duration === 'number') return duration; + const [, hours = 0, minutes = 0, secs = 0] = ISO_DURATION.exec(duration ?? '') || []; + return Number(hours) * 3600 + Number(minutes) * 60 + Number(secs); +} + +export const toDuration = (minutes) => `PT${Math.round(minutes)}M`; + +export function formatInterval(duration) { + const total = seconds(duration); + if (!total) return '—'; + if (total < 60) return `${total}s`; + const hours = Math.floor(total / 3600); + const minutes = Math.floor((total % 3600) / 60); + return [hours && `${hours}h`, minutes && `${minutes}m`].filter(Boolean).join(' '); +} + +export function bytes(size) { + if (!size) return '0 B'; + const units = ['B', 'KB', 'MB', 'GB', 'TB']; + let unit = 0; + let value = size; + while (value >= 1024 && unit < units.length - 1) { + value /= 1024; + unit++; + } + return `${value.toFixed(unit > 0 ? 1 : 0)} ${units[unit]}`; +} + +export function relativeTime(iso) { + const elapsed = Math.max(0, Math.floor((Date.now() - new Date(iso).getTime()) / 1000)); + if (elapsed < 60) return `${elapsed}s ago`; + const minutes = Math.floor(elapsed / 60); + if (minutes < 60) return `${minutes}m ago`; + const hours = Math.floor(minutes / 60); + if (hours < 24) return `${hours}h ago`; + return `${Math.floor(hours / 24)}d ago`; +} + +export function percent(written, total) { + return total > 0 ? Math.max(0, Math.min(100, Math.floor((written / total) * 100))) : 0; +} diff --git a/src/main/resources/static/js/main.js b/src/main/resources/static/js/main.js new file mode 100644 index 0000000..aaaa268 --- /dev/null +++ b/src/main/resources/static/js/main.js @@ -0,0 +1,50 @@ +import { initBackups } from './backups.js'; +import { initConnection } from './connection.js'; +import { createNotifier } from './notify.js'; +import { initPickupInterval } from './pickup-interval.js'; +import { initServerConfig } from './server-config.js'; +import { initViews } from './views.js'; + +const HEALTH_INTERVAL_MS = 7000; + +const notify = createNotifier(document.getElementById('banner')); +const pickupInterval = initPickupInterval(document.getElementById('pickupIntervalForm'), notify); +const serverConfig = initServerConfig(document.querySelector('[data-view="config"]'), notify); +const backups = initBackups({ + root: document.getElementById('backups'), + actions: document.getElementById('actions'), +}, notify, { refreshHealth: () => connection.refreshHealth() }); + +const connection = initConnection({ + root: document.getElementById('connection'), + statusPanel: document.getElementById('serverStatus'), + badge: document.getElementById('connBadge'), +}, notify, { + onServerChanged: () => { + backups.refresh(); + serverConfig.serverChanged(); + }, + onHealth: (health) => backups.setServerRunning(Boolean(health.serverStatus?.running)), + onStatus: (status) => pickupInterval.show(status.pickupInterval), +}); + +document.addEventListener('click', (event) => { + const button = event.target.closest('button'); + if (!button) return; + button.classList.add('clicked'); + setTimeout(() => button.classList.remove('clicked'), 140); +}); + +initViews((view) => { + notify.clear(); + if (view === 'config') serverConfig.load(); + else connection.refreshHealth(); +}); + +connection.refreshStatus().catch(notify.error).then(backups.refresh); +setInterval(() => { + if (!document.hidden) connection.refreshHealth(); +}, HEALTH_INTERVAL_MS); +document.addEventListener('visibilitychange', () => { + if (!document.hidden) connection.refreshHealth(); +}); diff --git a/src/main/resources/static/js/notify.js b/src/main/resources/static/js/notify.js new file mode 100644 index 0000000..ddbe743 --- /dev/null +++ b/src/main/resources/static/js/notify.js @@ -0,0 +1,12 @@ +export function createNotifier(banner) { + function show(message, kind) { + banner.textContent = message; + banner.className = `banner visible ${kind}`; + } + + return { + ok: (message) => show(message, 'ok'), + error: (error) => show(error.message || String(error), 'error'), + clear: () => { banner.className = 'banner'; }, + }; +} diff --git a/src/main/resources/static/js/pickup-interval.js b/src/main/resources/static/js/pickup-interval.js new file mode 100644 index 0000000..c071e5b --- /dev/null +++ b/src/main/resources/static/js/pickup-interval.js @@ -0,0 +1,25 @@ +import { api } from './api.js'; +import { seconds, toDuration } from './format.js'; + +export function initPickupInterval(form, notify) { + const minutes = form.elements.minutes; + + form.addEventListener('submit', async (event) => { + event.preventDefault(); + notify.clear(); + try { + const status = await api.updatePickupInterval(toDuration(Number(minutes.value))); + show(status.pickupInterval); + notify.ok('Pickup interval saved'); + } catch (error) { + notify.error(error); + } + }); + + function show(interval) { + const value = Math.round(seconds(interval) / 60); + if (value) minutes.value = value; + } + + return { show }; +} diff --git a/src/main/resources/static/js/server-config.js b/src/main/resources/static/js/server-config.js new file mode 100644 index 0000000..9a46998 --- /dev/null +++ b/src/main/resources/static/js/server-config.js @@ -0,0 +1,33 @@ +import { api } from './api.js'; +import { initServices } from './services.js'; +import { initSettings } from './settings.js'; + +export function initServerConfig(root, notify) { + const content = root.querySelector('[data-config-content]'); + const unavailable = root.querySelector('[data-unavailable]'); + const settings = initSettings(root.querySelector('#settingsForm'), notify); + const services = initServices(root.querySelector('#services'), notify); + + async function load() { + try { + const [config, list] = await Promise.all([api.serverConfig(), api.listServices()]); + settings.show(config); + services.show(list); + content.hidden = false; + unavailable.hidden = true; + } catch (error) { + content.hidden = true; + unavailable.hidden = false; + unavailable.querySelector('[data-reason]').textContent = + `${error.message}. Connect to a MediaGarrd server that has finished setup on the Dashboard to manage its configuration.`; + } + } + + return { + load, + serverChanged() { + services.resetForm(); + if (!root.hidden) load(); + }, + }; +} diff --git a/src/main/resources/static/js/services.js b/src/main/resources/static/js/services.js new file mode 100644 index 0000000..0c0ab09 --- /dev/null +++ b/src/main/resources/static/js/services.js @@ -0,0 +1,96 @@ +import { api } from './api.js'; + +export function initServices(root, notify) { + const form = root.querySelector('form'); + const title = root.querySelector('[data-form-title]'); + const paths = root.querySelector('[data-paths]'); + const cancel = root.querySelector('[data-cancel]'); + const rows = root.querySelector('tbody'); + const empty = root.querySelector('[data-empty]'); + const pathTemplate = root.querySelector('#pathTemplate'); + const rowTemplate = root.querySelector('#serviceTemplate'); + let editing = null; + + function addPathInput(value = '') { + const row = pathTemplate.content.firstElementChild.cloneNode(true); + row.querySelector('input').value = value; + row.querySelector('button').addEventListener('click', () => { + row.remove(); + if (!paths.children.length) addPathInput(); + }); + paths.append(row); + } + + function resetForm() { + editing = null; + form.reset(); + paths.replaceChildren(); + addPathInput(); + title.textContent = 'Add Service'; + cancel.hidden = true; + } + + function editService(service) { + editing = service.name; + form.elements.name.value = service.name; + paths.replaceChildren(); + service.paths.forEach((path) => addPathInput(path)); + title.textContent = `Edit ${service.name}`; + cancel.hidden = false; + form.elements.name.focus(); + } + + async function removeService(service) { + if (!confirm(`Remove ${service.name}? Existing backups are kept.`)) return; + notify.clear(); + try { + await api.removeService(service.name); + if (editing === service.name) resetForm(); + notify.ok(`Removed ${service.name}`); + await refresh(); + } catch (error) { + notify.error(error); + } + } + + function renderRow(service) { + const row = rowTemplate.content.firstElementChild.cloneNode(true); + row.querySelector('[data-name]').textContent = service.name; + row.querySelector('[data-paths]').textContent = service.paths.join('\n'); + row.querySelector('[data-edit]').addEventListener('click', () => editService(service)); + row.querySelector('[data-remove]').addEventListener('click', () => removeService(service)); + return row; + } + + function show(services) { + rows.replaceChildren(...services.map(renderRow)); + empty.hidden = services.length > 0; + } + + async function refresh() { + show(await api.listServices()); + } + + form.addEventListener('submit', async (event) => { + event.preventDefault(); + notify.clear(); + const service = { + name: form.elements.name.value, + paths: [...paths.querySelectorAll('input')].map((input) => input.value), + }; + try { + const saved = editing ? await api.updateService(editing, service) : await api.addService(service); + notify.ok(`Saved ${saved.name}`); + resetForm(); + await refresh(); + } catch (error) { + notify.error(error); + } + }); + + root.querySelector('[data-add-path]').addEventListener('click', () => addPathInput()); + cancel.addEventListener('click', resetForm); + + resetForm(); + return { show, resetForm }; +} diff --git a/src/main/resources/static/js/settings.js b/src/main/resources/static/js/settings.js new file mode 100644 index 0000000..cd2cf08 --- /dev/null +++ b/src/main/resources/static/js/settings.js @@ -0,0 +1,29 @@ +import { api } from './api.js'; +import { seconds, toDuration } from './format.js'; + +export function initSettings(form, notify) { + const { backupLocation, intervalHours, retentionCount } = form.elements; + + function show(config) { + backupLocation.value = config.backupLocation; + intervalHours.value = seconds(config.backupInterval) / 3600; + retentionCount.value = config.retentionCount; + } + + form.addEventListener('submit', async (event) => { + event.preventDefault(); + notify.clear(); + try { + show(await api.updateServerConfig({ + backupLocation: backupLocation.value, + retentionCount: Number(retentionCount.value), + backupInterval: toDuration(Number(intervalHours.value) * 60), + })); + notify.ok('Backup settings saved'); + } catch (error) { + notify.error(error); + } + }); + + return { show }; +} diff --git a/src/main/resources/static/js/views.js b/src/main/resources/static/js/views.js new file mode 100644 index 0000000..18bd5db --- /dev/null +++ b/src/main/resources/static/js/views.js @@ -0,0 +1,17 @@ +export function initViews(onShow) { + const views = document.querySelectorAll('[data-view]'); + const links = document.querySelectorAll('[data-view-link]'); + + function show() { + const current = location.hash === '#config' ? 'config' : 'dashboard'; + views.forEach((view) => { view.hidden = view.dataset.view !== current; }); + links.forEach((link) => link.setAttribute('aria-pressed', String(link.dataset.viewLink === current))); + onShow(current); + } + + links.forEach((link) => link.addEventListener('click', () => { + location.hash = link.dataset.viewLink === 'config' ? 'config' : ''; + })); + window.addEventListener('hashchange', show); + show(); +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/MediaGarrdTest.java b/src/test/java/wellatleastitried/mediagarrdclient/MediaGarrdTest.java new file mode 100644 index 0000000..2a6aa76 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/MediaGarrdTest.java @@ -0,0 +1,52 @@ +package wellatleastitried.mediagarrdclient; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.forwardedUrl; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import java.nio.file.Path; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.web.servlet.MockMvc; + +@SpringBootTest +@AutoConfigureMockMvc +class MediaGarrdTest { + + @TempDir + static Path dataDir; + + @Autowired + MockMvc mockMvc; + + @DynamicPropertySource + static void properties(DynamicPropertyRegistry registry) { + registry.add("mediagarrd.client.state-file", () -> dataDir.resolve("state.json").toString()); + registry.add("mediagarrd.client.download-directory", () -> dataDir.resolve("downloads").toString()); + registry.add("mediagarrd.client.preferred-server-ip", () -> ""); + } + + @Test + void servesTheWebPageAndItsAssets() throws Exception { + mockMvc.perform(get("/")).andExpect(status().isOk()).andExpect(forwardedUrl("index.html")); + mockMvc.perform(get("/css/mediagarrd.css")) + .andExpect(status().isOk()) + .andExpect(header().string("Cache-Control", "no-store")); + mockMvc.perform(get("/js/main.js")).andExpect(status().isOk()); + } + + @Test + void reportsStatusWithoutAServer() throws Exception { + mockMvc.perform(get("/api/client/status")) + .andExpect(status().isOk()) + .andExpect(content().json("{\"activeServer\":null,\"knownServers\":[]}")); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/api/ClientControllerTest.java b/src/test/java/wellatleastitried/mediagarrdclient/api/ClientControllerTest.java new file mode 100644 index 0000000..b59d047 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/api/ClientControllerTest.java @@ -0,0 +1,170 @@ +package wellatleastitried.mediagarrdclient.api; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import java.time.Duration; +import java.util.List; +import java.util.Optional; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; +import org.springframework.web.server.ResponseStatusException; + +import wellatleastitried.mediagarrdclient.dto.BackupDto; +import wellatleastitried.mediagarrdclient.dto.PickupStartDto; +import wellatleastitried.mediagarrdclient.service.BackupPickupService; +import wellatleastitried.mediagarrdclient.service.ClientStateService; +import wellatleastitried.mediagarrdclient.service.ServerApiService; +import wellatleastitried.mediagarrdclient.service.ServerDiscoveryService; + +@WebMvcTest(controllers = ClientController.class) +class ClientControllerTest { + + @Autowired + MockMvc mockMvc; + + @MockBean + ClientStateService stateService; + + @MockBean + ServerDiscoveryService discoveryService; + + @MockBean + ServerApiService serverApiService; + + @MockBean + BackupPickupService backupPickupService; + + @Test + void statusEndpointReturnsState() throws Exception { + when(stateService.getActiveServer()).thenReturn("http://server:8080"); + when(stateService.getPickupInterval()).thenReturn(Duration.ofMinutes(45)); + when(stateService.getKnownServers()).thenReturn(List.of("http://server:8080")); + + mockMvc.perform(get("/api/client/status")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.activeServer").value("http://server:8080")); + } + + @Test + void discoverEndpointReturnsOnlyTheServersFoundByTheScan() throws Exception { + when(discoveryService.discover()).thenReturn(List.of("http://server:8080")); + when(stateService.getKnownServers()).thenReturn(List.of("http://server:8080", "http://active:38471")); + + mockMvc.perform(post("/api/client/discover")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.length()").value(1)) + .andExpect(jsonPath("$[0]").value("http://server:8080")); + + verify(stateService).updateKnownServers(List.of("http://server:8080")); + } + + @Test + void listBackupsReturnsServerData() throws Exception { + when(stateService.requireActiveServer()).thenReturn("http://server:8080"); + when(serverApiService.listBackups("http://server:8080")).thenReturn(List.of(new BackupDto("id", "file.zip", 10L, null))); + + mockMvc.perform(get("/api/client/backups")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$[0].id").value("id")); + } + + @Test + void setServerEndpointAcceptsUpdate() throws Exception { + when(stateService.getKnownServers()).thenReturn(List.of("http://server:8080")); + when(stateService.getPickupInterval()).thenReturn(Duration.ofMinutes(30)); + when(stateService.getActiveServer()).thenReturn("http://server:8080"); + + mockMvc.perform(put("/api/client/server") + .contentType(MediaType.APPLICATION_JSON) + .content("{\"serverUrl\":\"http://server:8080\"}")) + .andExpect(status().isOk()); + } + + @Test + void pickupEndpointStartsTask() throws Exception { + when(backupPickupService.startPickupLatestTask()).thenReturn(new PickupStartDto("task-1", "id", "file.zip", 10L)); + + mockMvc.perform(post("/api/client/pickup")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.taskId").value("task-1")) + .andExpect(jsonPath("$.backupId").value("id")); + } + + @Test + void statusConnectsThePreferredServerFirst() throws Exception { + mockMvc.perform(get("/api/client/status")).andExpect(status().isOk()); + + verify(discoveryService).connectPreferredServer(); + } + + @Test + void normalizesSelectedServerUrls() throws Exception { + mockMvc.perform(json(put("/api/client/server"), "{\"serverUrl\":\" http://server:8080/ \"}")) + .andExpect(status().isOk()); + + verify(stateService).setActiveServer("http://server:8080"); + } + + @Test + void rejectsInvalidServerSelections() throws Exception { + mockMvc.perform(json(put("/api/client/server"), "{\"serverUrl\":\"ftp://server\"}")) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.error").value("serverUrl must be an http:// or https:// URL: ftp://server")); + mockMvc.perform(json(put("/api/client/server"), "{\"serverIp\":\"10.0.0.2\",\"serverPort\":70000}")) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.error").value("serverPort must be between 1 and 65535")); + mockMvc.perform(json(put("/api/client/server"), "{}")) + .andExpect(status().isBadRequest()); + mockMvc.perform(json(put("/api/client/server"), "not json")) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.error").value("Request body is missing or malformed")); + + verify(stateService, never()).setActiveServer(any()); + } + + @Test + void reportsWhenNoServerAnswersAtTheGivenAddress() throws Exception { + when(discoveryService.resolveServerByIp("10.0.0.2", null)).thenReturn(Optional.empty()); + + mockMvc.perform(json(put("/api/client/server"), "{\"serverIp\":\"10.0.0.2\"}")) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.error").value("No MediaGarrd server found at 10.0.0.2")); + } + + @Test + void rejectsInvalidPickupIntervals() throws Exception { + when(backupPickupService.updatePickupInterval(Duration.ZERO)).thenThrow(new IllegalArgumentException("Pickup interval must be a positive duration")); + + mockMvc.perform(json(put("/api/client/pickup-interval"), "{\"interval\":\"PT0S\"}")) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.error").value("Pickup interval must be a positive duration")); + } + + @Test + void unknownPickupTasksAreNotFound() throws Exception { + when(backupPickupService.pickupProgress("gone")).thenThrow(new ResponseStatusException(HttpStatus.NOT_FOUND, "Pickup task not found: gone")); + + mockMvc.perform(get("/api/client/pickup/progress/gone")) + .andExpect(status().isNotFound()) + .andExpect(jsonPath("$.error").value("Pickup task not found: gone")); + } + + private static MockHttpServletRequestBuilder json(MockHttpServletRequestBuilder request, String body) { + return request.contentType(MediaType.APPLICATION_JSON).content(body); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/api/ServerConfigControllerTest.java b/src/test/java/wellatleastitried/mediagarrdclient/api/ServerConfigControllerTest.java new file mode 100644 index 0000000..de33936 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/api/ServerConfigControllerTest.java @@ -0,0 +1,139 @@ +package wellatleastitried.mediagarrdclient.api; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import java.time.Duration; +import java.util.List; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; +import org.springframework.web.client.ResourceAccessException; +import org.springframework.web.server.ResponseStatusException; + +import wellatleastitried.mediagarrdclient.dto.ServerConfigDto; +import wellatleastitried.mediagarrdclient.dto.ServerStatusDto; +import wellatleastitried.mediagarrdclient.dto.ServiceDto; +import wellatleastitried.mediagarrdclient.service.ClientStateService; +import wellatleastitried.mediagarrdclient.service.ServerApiService; + +@WebMvcTest(controllers = ServerConfigController.class) +class ServerConfigControllerTest { + + private static final String SERVER = "http://server:8080"; + private static final ServiceDto RADARR = new ServiceDto("radarr", List.of("/srv/radarr")); + private static final String RADARR_JSON = """ + {"name": "radarr", "paths": ["/srv/radarr"]} + """; + + @Autowired + MockMvc mockMvc; + + @MockBean + ClientStateService stateService; + + @MockBean + ServerApiService serverApiService; + + @BeforeEach + void setUp() { + when(stateService.requireActiveServer()).thenReturn(SERVER); + } + + @Test + void returnsServerConfig() throws Exception { + when(serverApiService.serverConfig(SERVER)).thenReturn(new ServerConfigDto("/backups", 4, Duration.ofHours(6))); + + mockMvc.perform(get("/api/client/server-config")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.backupLocation").value("/backups")) + .andExpect(jsonPath("$.retentionCount").value(4)) + .andExpect(jsonPath("$.backupInterval").value("PT6H")); + } + + @Test + void updatesConfigAndScheduleTogether() throws Exception { + when(serverApiService.updateServerConfig(SERVER, "/new", 3)).thenReturn(new ServerConfigDto("/new", 3, Duration.ofHours(6))); + when(serverApiService.updateServerSchedule(SERVER, Duration.ofMinutes(90))) + .thenReturn(new ServerStatusDto(true, false, 3, Duration.ofMinutes(90))); + + mockMvc.perform(json(put("/api/client/server-config"), "{\"backupLocation\": \"/new\", \"retentionCount\": 3, \"backupInterval\": \"PT90M\"}")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.backupLocation").value("/new")) + .andExpect(jsonPath("$.retentionCount").value(3)) + .andExpect(jsonPath("$.backupInterval").value("PT1H30M")); + } + + @Test + void leavesScheduleAloneWhenIntervalIsOmitted() throws Exception { + when(serverApiService.updateServerConfig(SERVER, null, 5)).thenReturn(new ServerConfigDto("/backups", 5, Duration.ofHours(6))); + + mockMvc.perform(json(put("/api/client/server-config"), "{\"retentionCount\": 5}")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.backupInterval").value("PT6H")); + + verify(serverApiService, never()).updateServerSchedule(anyString(), any()); + } + + @Test + void forwardsServiceChanges() throws Exception { + when(serverApiService.listServices(SERVER)).thenReturn(List.of(RADARR)); + when(serverApiService.addService(SERVER, RADARR)).thenReturn(RADARR); + when(serverApiService.updateService(SERVER, "old name", RADARR)).thenReturn(RADARR); + + mockMvc.perform(get("/api/client/services")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$[0].name").value("radarr")) + .andExpect(jsonPath("$[0].paths[0]").value("/srv/radarr")); + mockMvc.perform(json(post("/api/client/services"), RADARR_JSON)) + .andExpect(status().isCreated()) + .andExpect(jsonPath("$.name").value("radarr")); + mockMvc.perform(json(put("/api/client/services/old name"), RADARR_JSON)) + .andExpect(status().isOk()); + mockMvc.perform(delete("/api/client/services/radarr")) + .andExpect(status().isNoContent()); + + verify(serverApiService).removeService(SERVER, "radarr"); + } + + @Test + void rejectsRequestsWithoutAnActiveServer() throws Exception { + when(stateService.requireActiveServer()) + .thenThrow(new ResponseStatusException(HttpStatus.BAD_REQUEST, "No active MediaGarrd server selected")); + + mockMvc.perform(get("/api/client/services")) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.error").value("No active MediaGarrd server selected")); + + verify(serverApiService, never()).listServices(anyString()); + } + + @Test + void reportsAnUnreachableServer() throws Exception { + when(serverApiService.serverConfig(SERVER)).thenThrow(new ResourceAccessException("Connection refused")); + + mockMvc.perform(get("/api/client/server-config")) + .andExpect(status().isBadGateway()) + .andExpect(jsonPath("$.error").value("MediaGarrd server is unreachable")); + } + + private static MockHttpServletRequestBuilder json(MockHttpServletRequestBuilder request, String body) { + return request.contentType(MediaType.APPLICATION_JSON).content(body); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/service/BackupPickupServiceTest.java b/src/test/java/wellatleastitried/mediagarrdclient/service/BackupPickupServiceTest.java new file mode 100644 index 0000000..4c39aa4 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/service/BackupPickupServiceTest.java @@ -0,0 +1,199 @@ +package wellatleastitried.mediagarrdclient.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.http.HttpStatus; +import org.springframework.web.server.ResponseStatusException; + +import wellatleastitried.mediagarrdclient.Configuration; +import wellatleastitried.mediagarrdclient.dto.BackupDto; +import wellatleastitried.mediagarrdclient.dto.PickupProgressDto; +import wellatleastitried.mediagarrdclient.dto.PickupStartDto; + +class BackupPickupServiceTest { + + private static final String SERVER = "http://server:8080"; + private static final BackupDto LATEST = new BackupDto("b2", "b2-media-backup.zip", 4, Instant.EPOCH); + private static final BackupDto OLDER = new BackupDto("b1", "b1-media-backup.zip", 4, Instant.EPOCH); + + @TempDir + Path downloads; + + private final ClientStateService state = mock(ClientStateService.class); + private final ServerApiService api = mock(ServerApiService.class); + private final MutableClock clock = new MutableClock(); + private BackupPickupService pickup; + + @BeforeEach + void setUp() { + Configuration configuration = new Configuration(); + configuration.setDownloadDirectory(downloads.toString()); + when(state.requireActiveServer()).thenReturn(SERVER); + when(state.getPickupInterval()).thenReturn(Duration.ofHours(1)); + when(api.listBackups(SERVER)).thenReturn(List.of(LATEST, OLDER)); + pickup = new BackupPickupService(configuration, state, api, clock); + } + + @AfterEach + void tearDown() { + pickup.shutdown(); + } + + @Test + void downloadsTheLatestBackup() throws Exception { + when(api.downloadById(eq(SERVER), eq("b2"), any(), any())).thenAnswer(invocation -> invocation.getArgument(2)); + + PickupStartDto started = pickup.startPickupLatestTask(); + PickupProgressDto progress = awaitFinished(started.taskId()); + + assertEquals("COMPLETED", progress.status()); + assertEquals(downloads.resolve("b2-media-backup.zip").toString(), progress.savedPath()); + } + + @Test + void reusesTheRunningTaskForTheSameBackup() throws Exception { + CountDownLatch release = new CountDownLatch(1); + when(api.downloadById(eq(SERVER), eq("b2"), any(), any())).thenAnswer(invocation -> { + release.await(5, TimeUnit.SECONDS); + return invocation.getArgument(2); + }); + + PickupStartDto first = pickup.startPickupLatestTask(); + PickupStartDto second = pickup.startPickupByIdTask("b2"); + release.countDown(); + awaitFinished(first.taskId()); + + assertEquals(first.taskId(), second.taskId()); + verify(api, times(1)).downloadById(anyString(), anyString(), any(), any()); + } + + @Test + void reusesAnExistingDownload() throws Exception { + Files.write(downloads.resolve("b1-media-backup.zip"), new byte[4]); + + PickupProgressDto progress = pickup.pickupProgress(pickup.startPickupByIdTask("b1").taskId()); + + assertEquals("COMPLETED", progress.status()); + verify(api, never()).downloadById(anyString(), anyString(), any(), any()); + } + + @Test + void reportsDownloadFailures() throws Exception { + when(api.downloadById(eq(SERVER), eq("b2"), any(), any())).thenThrow(new IllegalStateException("disk full")); + + PickupProgressDto progress = awaitFinished(pickup.startPickupLatestTask().taskId()); + + assertEquals("FAILED", progress.status()); + assertEquals("disk full", progress.error()); + } + + @Test + void forgetsFinishedTasksAfterTheRetentionPeriod() throws Exception { + Files.write(downloads.resolve("b1-media-backup.zip"), new byte[4]); + String taskId = pickup.startPickupByIdTask("b1").taskId(); + + clock.advance(BackupPickupService.FINISHED_TASK_RETENTION.plusSeconds(1)); + pickup.startPickupByIdTask("b1"); + + assertStatus(HttpStatus.NOT_FOUND, () -> pickup.pickupProgress(taskId)); + } + + @Test + void rejectsUnknownBackupsAndTasks() { + assertStatus(HttpStatus.NOT_FOUND, () -> pickup.startPickupByIdTask("missing")); + assertStatus(HttpStatus.NOT_FOUND, () -> pickup.pickupProgress("missing")); + when(api.listBackups(SERVER)).thenReturn(List.of()); + assertStatus(HttpStatus.NOT_FOUND, () -> pickup.startPickupLatestTask()); + } + + @Test + void refusesFileNamesThatLeaveTheDownloadDirectory() { + when(api.listBackups(SERVER)).thenReturn(List.of(new BackupDto("evil", "../evil.zip", 4, Instant.EPOCH))); + + assertThrows(IllegalArgumentException.class, () -> pickup.startPickupLatestTask()); + } + + @Test + void scheduledPickupKeepsOnlyTheLatestAutomaticDownload() throws IOException { + Files.write(downloads.resolve("b1-media-backup-AD.zip"), new byte[4]); + Files.write(downloads.resolve("b2-media-backup.zip"), new byte[3]); + when(api.downloadById(eq(SERVER), eq("b2"), any(), any())).thenAnswer(invocation -> { + Path target = invocation.getArgument(2); + Files.write(target, new byte[4]); + return target; + }); + + clock.advance(Duration.ofHours(2)); + pickup.scheduledPickup(); + + assertEquals(List.of("b2-media-backup-AD.zip", "b2-media-backup.zip"), fileNames()); + } + + private PickupProgressDto awaitFinished(String taskId) throws InterruptedException { + for (int attempt = 0; attempt < 200; attempt++) { + PickupProgressDto progress = pickup.pickupProgress(taskId); + if (progress.status().equals("COMPLETED") || progress.status().equals("FAILED")) { + return progress; + } + Thread.sleep(10); + } + throw new AssertionError("Pickup task " + taskId + " did not finish"); + } + + private List fileNames() throws IOException { + try (var files = Files.list(downloads)) { + return files.map(path -> path.getFileName().toString()).sorted().toList(); + } + } + + private static void assertStatus(HttpStatus status, Runnable action) { + assertEquals(status, assertThrows(ResponseStatusException.class, action::run).getStatusCode()); + } + + private static final class MutableClock extends Clock { + private Instant now = Instant.parse("2026-10-26T00:00:00Z"); + + void advance(Duration duration) { + now = now.plus(duration); + } + + @Override + public Instant instant() { + return now; + } + + @Override + public java.time.ZoneId getZone() { + return ZoneOffset.UTC; + } + + @Override + public Clock withZone(java.time.ZoneId zone) { + return this; + } + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/service/ClientStateServiceTest.java b/src/test/java/wellatleastitried/mediagarrdclient/service/ClientStateServiceTest.java new file mode 100644 index 0000000..0fb435d --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/service/ClientStateServiceTest.java @@ -0,0 +1,103 @@ +package wellatleastitried.mediagarrdclient.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Duration; +import java.util.List; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.web.server.ResponseStatusException; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import wellatleastitried.mediagarrdclient.Configuration; + +class ClientStateServiceTest { + + private static final ObjectMapper MAPPER = new ObjectMapper(); + + @TempDir + Path tempDir; + + private final Configuration configuration = new Configuration(); + + @BeforeEach + void setUp() { + configuration.setStateFile(tempDir.resolve("state.json").toString()); + configuration.setPickupInterval(Duration.ofHours(12)); + } + + @Test + void persistsAndLoadsState() { + ClientStateService state = new ClientStateService(configuration, MAPPER); + state.updateKnownServers(List.of("http://a:8080", "http://b:8080")); + state.setActiveServer("http://b:8080"); + state.setPickupInterval(Duration.ofMinutes(30)); + + ClientStateService reloaded = new ClientStateService(configuration, MAPPER); + assertEquals("http://b:8080", reloaded.getActiveServer()); + assertEquals(Duration.ofMinutes(30), reloaded.getPickupInterval()); + assertEquals(List.of("http://a:8080", "http://b:8080"), reloaded.getKnownServers()); + assertEquals(List.of("state.json"), fileNames()); + } + + @Test + void keepsTheActiveServerWhenARescanDoesNotFindIt() { + ClientStateService state = new ClientStateService(configuration, MAPPER); + state.setActiveServer("http://a:8080"); + + state.updateKnownServers(List.of("http://b:8080")); + + assertEquals("http://a:8080", state.getActiveServer()); + assertEquals(List.of("http://b:8080", "http://a:8080"), state.getKnownServers()); + } + + @Test + void selectsTheFirstDiscoveredServerWhenNoneIsActive() { + ClientStateService state = new ClientStateService(configuration, MAPPER); + + state.updateKnownServers(List.of("http://b:8080", "http://b:8080", "http://c:8080")); + + assertEquals("http://b:8080", state.getActiveServer()); + assertEquals(List.of("http://b:8080", "http://c:8080"), state.getKnownServers()); + } + + @Test + void rejectsNonPositivePickupIntervals() { + ClientStateService state = new ClientStateService(configuration, MAPPER); + + assertThrows(IllegalArgumentException.class, () -> state.setPickupInterval(Duration.ZERO)); + assertThrows(IllegalArgumentException.class, () -> state.setPickupInterval(null)); + assertEquals(Duration.ofHours(12), state.getPickupInterval()); + } + + @Test + void requiresAnActiveServer() { + assertThrows(ResponseStatusException.class, () -> new ClientStateService(configuration, MAPPER).requireActiveServer()); + } + + @Test + void startsWithDefaultsWhenTheStateFileIsUnreadable() throws IOException { + Files.writeString(tempDir.resolve("state.json"), "{not json"); + + ClientStateService state = new ClientStateService(configuration, MAPPER); + + assertNull(state.getActiveServer()); + assertEquals(Duration.ofHours(12), state.getPickupInterval()); + } + + private List fileNames() { + try (var files = Files.list(tempDir)) { + return files.map(path -> path.getFileName().toString()).sorted().toList(); + } catch (IOException e) { + throw new IllegalStateException(e); + } + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/service/ServerApiServiceTest.java b/src/test/java/wellatleastitried/mediagarrdclient/service/ServerApiServiceTest.java new file mode 100644 index 0000000..bd3f4ba --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/service/ServerApiServiceTest.java @@ -0,0 +1,123 @@ +package wellatleastitried.mediagarrdclient.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.io.IOException; +import java.io.OutputStream; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.RestClientResponseException; + +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpServer; + +import wellatleastitried.mediagarrdclient.api.ApiExceptionHandler; +import wellatleastitried.mediagarrdclient.dto.ServerConfigDto; +import wellatleastitried.mediagarrdclient.dto.ServiceDto; + +class ServerApiServiceTest { + + private record Exchange(String method, String path, String body) { + } + + private final List exchanges = new ArrayList<>(); + private final ServerApiService service = new ServerApiService(); + private HttpServer server; + private String serverUrl; + private int status = 200; + private String response = "{}"; + + @BeforeEach + void startServer() throws IOException { + server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + server.createContext("/", this::handle); + server.start(); + serverUrl = "http://127.0.0.1:" + server.getAddress().getPort(); + } + + @AfterEach + void stopServer() { + server.stop(0); + } + + @Test + void sendsConfigUpdatesWithOmittedFieldsAsNull() { + response = "{\"backupLocation\": \"/backups\", \"retentionCount\": 5, \"backupInterval\": \"PT6H\"}"; + + ServerConfigDto config = service.updateServerConfig(serverUrl, null, 5); + + assertEquals(new ServerConfigDto("/backups", 5, Duration.ofHours(6)), config); + assertEquals(new Exchange("PUT", "/api/v1/config", "{\"backupLocation\":null,\"retentionCount\":5}"), exchanges.getFirst()); + } + + @Test + void sendsScheduleAsIsoDuration() { + response = "{\"healthy\": true, \"running\": false, \"backupRetentionCount\": 4, \"backupInterval\": \"PT1H30M\"}"; + + assertEquals(Duration.ofMinutes(90), service.updateServerSchedule(serverUrl, Duration.ofMinutes(90)).backupInterval()); + assertEquals(new Exchange("PUT", "/api/v1/schedule", "{\"backupInterval\":\"PT1H30M\"}"), exchanges.getFirst()); + } + + @Test + void encodesServiceNamesInPaths() { + ServiceDto radarr = new ServiceDto("radarr", List.of("/srv/radarr")); + response = "{\"name\": \"radarr\", \"paths\": [\"/srv/radarr\"]}"; + + assertEquals(radarr, service.updateService(serverUrl, "old name", radarr)); + status = 204; + service.removeService(serverUrl, "radarr"); + + assertEquals("/api/v1/services/old%20name", exchanges.get(0).path()); + assertEquals(new Exchange("DELETE", "/api/v1/services/radarr", ""), exchanges.get(1)); + } + + @Test + void forwardsTheServerErrorMessageAndStatus() { + status = 409; + response = "{\"error\": \"Service already exists: radarr\"}"; + + RestClientResponseException e = assertThrows(RestClientResponseException.class, + () -> service.addService(serverUrl, new ServiceDto("radarr", List.of("/srv/radarr")))); + ResponseEntity forwarded = new ApiExceptionHandler().serverRejected(e); + + assertEquals(HttpStatus.CONFLICT, forwarded.getStatusCode()); + assertEquals(Map.of("error", "Service already exists: radarr"), forwarded.getBody()); + } + + @Test + void fallsBackToTheStatusWhenTheServerSendsNoMessage() { + status = 502; + response = "Bad Gateway"; + + RestClientResponseException e = assertThrows(RestClientResponseException.class, () -> service.serverConfig(serverUrl)); + + assertEquals(Map.of("error", "MediaGarrd server responded with 502"), new ApiExceptionHandler().serverRejected(e).getBody()); + } + + private void handle(HttpExchange exchange) throws IOException { + String body = new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8); + exchanges.add(new Exchange(exchange.getRequestMethod(), exchange.getRequestURI().getRawPath(), body)); + byte[] bytes = response.getBytes(StandardCharsets.UTF_8); + exchange.getResponseHeaders().add("Content-Type", "application/json"); + if (status == 204) { + exchange.sendResponseHeaders(204, -1); + } else { + exchange.sendResponseHeaders(status, bytes.length); + try (OutputStream out = exchange.getResponseBody()) { + out.write(bytes); + } + } + exchange.close(); + } +} diff --git a/src/test/java/wellatleastitried/mediagarrdclient/service/ServerDiscoveryServiceTest.java b/src/test/java/wellatleastitried/mediagarrdclient/service/ServerDiscoveryServiceTest.java new file mode 100644 index 0000000..fd527b3 --- /dev/null +++ b/src/test/java/wellatleastitried/mediagarrdclient/service/ServerDiscoveryServiceTest.java @@ -0,0 +1,165 @@ +package wellatleastitried.mediagarrdclient.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.IOException; +import java.io.OutputStream; +import java.net.Inet4Address; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.List; +import java.util.Optional; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.sun.net.httpserver.HttpServer; + +import wellatleastitried.mediagarrdclient.Configuration; +import wellatleastitried.mediagarrdclient.service.ServerDiscoveryService.HostInput; + +class ServerDiscoveryServiceTest { + + private static final String HEALTH = "{\"healthy\":true,\"running\":false,\"backupRetentionCount\":4,\"backupInterval\":\"PT6H\"}"; + + private final Configuration configuration = new Configuration(); + private final ClientStateService state = mock(ClientStateService.class); + private final ServerDiscoveryService discovery = new ServerDiscoveryService(configuration, state, new ObjectMapper()); + private HttpServer mediaGarrd; + private HttpServer otherApp; + + @BeforeEach + void startServers() throws IOException { + mediaGarrd = serve(HEALTH); + otherApp = serve("ok"); + } + + @AfterEach + void stopServers() { + mediaGarrd.stop(0); + otherApp.stop(0); + discovery.shutdown(); + } + + @Test + void resolvesTheGivenPort() { + assertEquals(Optional.of(url(mediaGarrd)), discovery.resolveServerByIp("127.0.0.1", port(mediaGarrd))); + } + + @Test + void readsThePortFromTheAddress() { + assertEquals(Optional.of(url(mediaGarrd)), discovery.resolveServerByIp("127.0.0.1:" + port(mediaGarrd), null)); + } + + @Test + void scansEveryPortWhenTheGivenPortIsNotAMediaGarrdServer() { + long start = System.nanoTime(); + + Optional found = discovery.resolveServerByIp("127.0.0.1", port(otherApp)); + + assertTrue(found.isPresent(), "no MediaGarrd server found by the port scan"); + assertNotEquals(url(otherApp), found.get()); + assertTrue(Duration.ofNanos(System.nanoTime() - start).toSeconds() < 15, "full port scan took too long"); + } + + @Test + void preferredServerIsResolvedFromConfiguration() { + configuration.setPreferredServerIp("localhost:" + port(mediaGarrd)); + + assertEquals(Optional.of("http://localhost:" + port(mediaGarrd)), discovery.resolvePreferredServer()); + } + + @Test + void connectsThePreferredServerOnlyWhileNoneIsSelected() { + configuration.setPreferredServerIp("127.0.0.1:" + port(mediaGarrd)); + + discovery.connectPreferredServer(); + when(state.getActiveServer()).thenReturn("http://other:38471"); + discovery.connectPreferredServer(); + + verify(state, times(1)).setActiveServer(url(mediaGarrd)); + } + + @Test + void givesUpQuicklyOnAnUnreachableHost() { + long start = System.nanoTime(); + + assertEquals(Optional.empty(), discovery.resolveServerByIp("192.0.2.1", 8123)); + assertTrue(Duration.ofNanos(System.nanoTime() - start).toSeconds() < 3, "unreachable host was port scanned"); + } + + @Test + void ignoresUnresolvableHosts() { + assertEquals(Optional.empty(), discovery.resolveServerByIp("no-such-host.invalid", null)); + assertEquals(Optional.empty(), discovery.resolveServerByIp(" ", null)); + } + + @Test + void rejectsHealthResponsesThatAreNotFromAMediaGarrdServer() throws IOException { + HttpServer lookalike = serve("{\"status\":\"UP\"}"); + try { + InetAddress loopback = InetAddress.getLoopbackAddress(); + assertFalse(discovery.isMediaGarrdServer(new ServerDiscoveryService.Candidate("127.0.0.1", loopback, port(lookalike)))); + assertFalse(discovery.isMediaGarrdServer(new ServerDiscoveryService.Candidate("127.0.0.1", loopback, port(otherApp)))); + assertTrue(discovery.isMediaGarrdServer(new ServerDiscoveryService.Candidate("127.0.0.1", loopback, port(mediaGarrd)))); + } finally { + lookalike.stop(0); + } + } + + @ParameterizedTest + @CsvSource({"24, 254, 192.168.1.1, 192.168.1.254", "16, 254, 192.168.1.1, 192.168.1.254", "30, 2, 192.168.1.77, 192.168.1.78", "32, 2, 192.168.1.77, 192.168.1.78"}) + void listsTheHostsOfTheLocalSubnet(int prefix, int count, String first, String last) throws IOException { + List hosts = ServerDiscoveryService.subnetHosts((Inet4Address) InetAddress.getByName("192.168.1.77"), prefix); + + assertEquals(count, hosts.size()); + assertEquals(first, hosts.getFirst().getHostAddress()); + assertEquals(last, hosts.getLast().getHostAddress()); + } + + @ParameterizedTest + @CsvSource(value = {"192.168.1.5, 192.168.1.5, null", "192.168.1.5:9000, 192.168.1.5, 9000", "http://server:38471/, server, 38471", "[::1]:8080, ::1, 8080"}, nullValues = "null") + void parsesHostsWithOptionalPorts(String input, String host, Integer port) { + assertEquals(new HostInput(host, port), ServerDiscoveryService.parseHost(input)); + } + + @Test + void rejectsInputWithoutAHost() { + assertNull(ServerDiscoveryService.parseHost("http://")); + } + + private static HttpServer serve(String body) throws IOException { + HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + server.createContext("/", exchange -> { + byte[] bytes = body.getBytes(StandardCharsets.UTF_8); + exchange.sendResponseHeaders(200, bytes.length); + try (OutputStream out = exchange.getResponseBody()) { + out.write(bytes); + } + }); + server.start(); + return server; + } + + private static int port(HttpServer server) { + return server.getAddress().getPort(); + } + + private static String url(HttpServer server) { + return "http://127.0.0.1:" + port(server); + } +} diff --git a/src/test/java/wellatleastitried/mediaguardclient/api/ClientControllerTest.java b/src/test/java/wellatleastitried/mediaguardclient/api/ClientControllerTest.java deleted file mode 100644 index df656cc..0000000 --- a/src/test/java/wellatleastitried/mediaguardclient/api/ClientControllerTest.java +++ /dev/null @@ -1,97 +0,0 @@ -package wellatleastitried.mediagarrdclient.api; - -import static org.mockito.Mockito.when; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -import java.nio.file.Path; -import java.time.Duration; -import java.util.List; - -import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; -import org.springframework.boot.test.mock.mockito.MockBean; -import org.springframework.http.MediaType; -import org.springframework.test.web.servlet.MockMvc; - -import wellatleastitried.mediagarrdclient.dto.BackupDto; -import wellatleastitried.mediagarrdclient.service.BackupPickupService; -import wellatleastitried.mediagarrdclient.service.ClientStateService; -import wellatleastitried.mediagarrdclient.service.ServerApiService; -import wellatleastitried.mediagarrdclient.service.ServerDiscoveryService; - -@WebMvcTest(controllers = ClientController.class) -class ClientControllerTest { - - @Autowired - MockMvc mockMvc; - - @MockBean - ClientStateService stateService; - - @MockBean - ServerDiscoveryService discoveryService; - - @MockBean - ServerApiService serverApiService; - - @MockBean - BackupPickupService backupPickupService; - - @Test - void statusEndpointReturnsState() throws Exception { - when(stateService.getActiveServer()).thenReturn("http://server:8080"); - when(stateService.getPickupInterval()).thenReturn(Duration.ofMinutes(45)); - when(stateService.getKnownServers()).thenReturn(List.of("http://server:8080")); - - mockMvc.perform(get("/api/client/status")) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.activeServer").value("http://server:8080")); - } - - @Test - void discoverEndpointUpdatesState() throws Exception { - when(discoveryService.discover()).thenReturn(List.of("http://server:8080")); - when(stateService.getKnownServers()).thenReturn(List.of("http://server:8080")); - when(stateService.getPickupInterval()).thenReturn(Duration.ofMinutes(30)); - when(stateService.getActiveServer()).thenReturn("http://server:8080"); - - mockMvc.perform(post("/api/client/discover")) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.knownServers[0]").value("http://server:8080")); - } - - @Test - void listBackupsReturnsServerData() throws Exception { - when(stateService.getActiveServer()).thenReturn("http://server:8080"); - when(serverApiService.listBackups("http://server:8080")).thenReturn(List.of(new BackupDto("id", "file.zip", 10L, null))); - - mockMvc.perform(get("/api/client/backups")) - .andExpect(status().isOk()) - .andExpect(jsonPath("$[0].id").value("id")); - } - - @Test - void setServerEndpointAcceptsUpdate() throws Exception { - when(stateService.getKnownServers()).thenReturn(List.of("http://server:8080")); - when(stateService.getPickupInterval()).thenReturn(Duration.ofMinutes(30)); - when(stateService.getActiveServer()).thenReturn("http://server:8080"); - - mockMvc.perform(put("/api/client/server") - .contentType(MediaType.APPLICATION_JSON) - .content("{\"serverUrl\":\"http://server:8080\"}")) - .andExpect(status().isOk()); - } - - @Test - void pickupEndpointReturnsPath() throws Exception { - when(backupPickupService.pickupLatest()).thenReturn(Path.of("/tmp/latest.zip")); - - mockMvc.perform(post("/api/client/pickup")) - .andExpect(status().isOk()); - } -} diff --git a/src/test/java/wellatleastitried/mediaguardclient/service/ClientStateServiceTest.java b/src/test/java/wellatleastitried/mediaguardclient/service/ClientStateServiceTest.java deleted file mode 100644 index e4ef030..0000000 --- a/src/test/java/wellatleastitried/mediaguardclient/service/ClientStateServiceTest.java +++ /dev/null @@ -1,35 +0,0 @@ -package wellatleastitried.mediagarrdclient.service; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.nio.file.Path; -import java.time.Duration; -import java.util.List; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; - -import wellatleastitried.mediagarrdclient.Configuration; - -class ClientStateServiceTest { - - @TempDir - Path tempDir; - - @Test - void persistsAndLoadsState() { - Configuration cfg = new Configuration(); - cfg.setStateFile(tempDir.resolve("state.json").toString()); - cfg.setPickupInterval(Duration.ofHours(12)); - - ClientStateService state = new ClientStateService(cfg); - state.updateKnownServers(List.of("http://a:8080", "http://b:8080")); - state.setActiveServer("http://b:8080"); - state.setPickupInterval(Duration.ofMinutes(30)); - - ClientStateService reloaded = new ClientStateService(cfg); - assertEquals("http://b:8080", reloaded.getActiveServer()); - assertEquals(Duration.ofMinutes(30), reloaded.getPickupInterval()); - assertEquals(2, reloaded.getKnownServers().size()); - } -}