diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..95984da --- /dev/null +++ b/.dockerignore @@ -0,0 +1,5 @@ +target/ +docker/ +.git/ +.idea/ +*.iml diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml new file mode 100644 index 0000000..79502f0 --- /dev/null +++ b/.github/workflows/tests.yml @@ -0,0 +1,42 @@ +name: Tests + +on: + push: + branches-ignore: + - main + pull_request: + +permissions: + contents: read + +concurrency: + group: tests-${{ github.workflow }}-${{ github.event_name }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + test: + name: Java ${{ matrix.java }} + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + # The Java versions required by the supported Minecraft versions (1.18–1.20.4, 1.20.5–1.21.x, 26.x). + java: [17, 21, 25] + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: ${{ matrix.java }} + cache: maven + + - name: Build and test + run: mvn -B verify + + - name: Upload test reports + if: failure() + uses: actions/upload-artifact@v4 + with: + name: surefire-reports-java-${{ matrix.java }} + path: target/surefire-reports/ diff --git a/.gitignore b/.gitignore index 5ff6309..33fab89 100644 --- a/.gitignore +++ b/.gitignore @@ -4,10 +4,7 @@ target/ !**/src/test/**/target/ ### IntelliJ IDEA ### -.idea/modules.xml -.idea/jarRepositories.xml -.idea/compiler.xml -.idea/libraries/ +.idea/ *.iws *.iml *.ipr @@ -35,4 +32,6 @@ build/ .vscode/ ### Mac OS ### -.DS_Store \ No newline at end of file +.DS_Store +### Docker development ### +docker/plugins/*.jar diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..305a2f2 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,13 @@ +# Build and test image: JDK + Maven, nothing else needed on the host. +# docker compose run --rm build +FROM maven:3.9-eclipse-temurin-21 + +WORKDIR /workspace + +# Resolve dependencies in their own layer so source changes don't re-download them. +COPY pom.xml . +RUN mvn -B -q dependency:go-offline || true + +COPY src ./src + +CMD ["mvn", "-B", "verify"] diff --git a/README-PL.md b/README-PL.md index af0a063..549e3f9 100644 --- a/README-PL.md +++ b/README-PL.md @@ -1,61 +1,30 @@ -Angielska wersja znajduje się [tutaj](README.md). - # VoteReward -VoteReward to plugin pod Spigot pozwalający na przyznawanie nagród graczom za głosowanie na serwer. Został stworzony pod -wersje powyżej 1.18. Statystyki projektu dostępne na -stronie [bStats](https://bstats.org/plugin/bukkit/VoteReward/20120). - -# Instalacja - -Pobierz najnowszą wersję pluginu [tutaj](https://github.com/dudekm/VoteReward/releases/latest). - -Po pobraniu pliku `.jar`, należy umieścić go w folderze "plugins" w głównym katalogu serwera, a następnie zrestartować -serwer. Po ponownym uruchomieniu powinien zostać utworzony folder "VoteReward" zawierający plik konfiguracyjny. - -Teraz w `settings.yml` należy skonfigurować serwery, na które mogą głosować gracze. W tym celu przechodzimy do -sekcji `servers`. Jej domyślna forma wygląda następująco: - -```yaml -servers: - lista-minecraft: - address: https://lista-minecraft.pl - uuid: 183413bc-4588-4265-8f06-346963e5d7df - reward-commands: - - xp add %player_name% 100 - - give %player_name% diamond - lista-serwerow-emecz: - address: https://lista-serwerow.emecz.pl - uuid: 264acafc-136c-4def-a363-088587c7a405 - reward-commands: [] - minecraft-list: - address: https://minecraft-list.info - uuid: d6dfe480-da3a-495a-a92d-5a198a7f2f83 - reward-commands: [] -``` - -Wartości "lista-minecraft" czy "lista-serwerow-emecz" mogą być czymkolwiek - są to tylko nazwy. Nazwy powinny być -unikatowe dla każdego serwera. Można dodać tyle serwerów, ile jest potrzebne. +[English](README.md) -`address` odnosi się do adresu strony, na której dodano serwer. Wspierane adresy to: +Plugin nagradzający graczy za głosowanie na serwer na listach serwerów +([lista-minecraft.pl](https://lista-minecraft.pl), [lista-serwerow.emecz.pl](https://lista-serwerow.emecz.pl), +[minecraft-list.info](https://minecraft-list.info)). Co 30 sekund (konfigurowalne) sprawdza nowe głosy przez API +list i automatycznie wykonuje komendy nagród — od razu, albo przy najbliższym wejściu gracza na serwer. -- https://lista-minecraft.pl, -- https://lista-serwerow.emecz.pl, -- https://minecraft-list.info. +- **Minecraft:** 1.18 – 26.3 +- **Silniki:** Spigot, Paper, Purpur, Folia i inne zgodne z Bukkit API (szczegóły w [instalacji](docs/pl/installation.md#obsługiwane-serwery)) +- **Java:** 17+ (taka, jakiej wymaga wersja Minecrafta) +- Statystyki: [bStats](https://bstats.org/plugin/bukkit/VoteReward/20120) -`uuid` oznacza unikatowe ID serwera przypisane wyłącznie do niego. Aby sprawdzić ID, należy wejść na stronę serwera i -skopiować ostatni element adresu strony. Przykładowo, jeżeli wygląda on -następująco: https://lista-minecraft.pl/serwery/minecraft/183413bc-4588-4265-8f06-346963e5d7df - ID będzie -równe `183413bc-4588-4265-8f06-346963e5d7df`. +## Dokumentacja -`reward-commands` to lista komend, które zostaną wysłane do konsoli serwera po pomyślnym zweryfikowaniu głosu gracza. -Dostępne są następujące symbole zastępcze (placeholdery): +| | | +|---|---| +| [Instalacja](docs/pl/installation.md) | wymagania, obsługiwane serwery, aktualizacja z 3.x | +| [Konfiguracja](docs/pl/configuration.md) | `settings.yml`, `messages.yml`, komendy i uprawnienia | +| [Jak to działa](docs/pl/architecture.md) | odpytywanie API, zasady nagród, struktura kodu | +| [Development](docs/pl/development.md) | budowanie, Docker, serwer testowy z atrapą API | +| [Testy](docs/pl/testing.md) | uruchamianie testów, co jest testowane, jak pisać nowe | +| [Release](docs/pl/release.md) | wydawanie nowej wersji | -- `%player_name%` - nazwa gracza, -- `%player_display_name%` - wyświetlana nazwa gracza, -- `%player_uuid%` - unikatowe ID gracza, -- `%server_name%` - nazwa serwera, -- `%server_address%` - adres strony serwera. +## Szybki start -Jeżeli plugin został poprawnie skonfigurowany, gracz po oddaniu głosu może użyć komendy `/votereward`, aby otrzymać -nagrodę za głosowanie. \ No newline at end of file +1. Pobierz `VoteReward-.jar` z [Releases](https://github.com/dudekm/VoteReward/releases/latest) i wrzuć do `plugins/`. +2. Uruchom serwer, a potem w `plugins/VoteReward/settings.yml` wpisz `uuid` swojego serwera z każdej listy i komendy nagród. +3. `/votereward reload`. diff --git a/README.md b/README.md index 939e710..50b8d36 100644 --- a/README.md +++ b/README.md @@ -1,61 +1,30 @@ -The Polish version can be found [here](README-PL.md). - # VoteReward -VoteReward is a Spigot plugin that allows you to award players rewards for voting on a server. It was created for -versions above 1.18. Project statistics available on the [bStats](https://bstats.org/plugin/bukkit/VoteReward/20120) -website. - -# Installation - -Download the latest version of the plugin [here](https://github.com/dudekm/VoteReward/releases/latest). - -After downloading the `.jar` file, place it in the "plugins" folder in the main server directory and then restart the -server. After restarting, a "VoteReward" folder should be created containing the configuration file. - -Now in `settings.yml` you need to configure the servers that players can vote for. To do this, go to the `servers` -section. Its default form looks like this: - -```yaml -servers: - lista-minecraft: - address: https://lista-minecraft.pl - uuid: 183413bc-4588-4265-8f06-346963e5d7df - reward-commands: - - xp add %player_name% 100 - - give %player_name% diamond - lista-serwerow-emecz: - address: https://lista-serwerow.emecz.pl - uuid: 264acafc-136c-4def-a363-088587c7a405 - reward-commands: [] - minecraft-list: - address: https://minecraft-list.info - uuid: d6dfe480-da3a-495a-a92d-5a198a7f2f83 - reward-commands: [] -``` - -The values "lista-minecraft" or "lista-serwerow-emecz" can be anything - they are just names. Names should be unique for -each server. As many servers can be added as needed. +[Polski](README-PL.md) -`address` refers to the address of the page where the server was added. Supported addresses are: +A plugin that rewards players for voting for your server on server lists +([lista-minecraft.pl](https://lista-minecraft.pl), [lista-serwerow.emecz.pl](https://lista-serwerow.emecz.pl), +[minecraft-list.info](https://minecraft-list.info)). Every 30 seconds (configurable) it checks the lists' APIs for new +votes and automatically runs the reward commands — right away, or the next time the player joins the server. -- https://lista-minecraft.pl, -- https://lista-serwerow.emecz.pl, -- https://minecraft-list.info. +- **Minecraft:** 1.18 – 26.3 +- **Server software:** Spigot, Paper, Purpur, Folia and others compatible with the Bukkit API (see [installation](docs/installation.md#supported-servers)) +- **Java:** 17+ (whatever your Minecraft version requires) +- Statistics: [bStats](https://bstats.org/plugin/bukkit/VoteReward/20120) -`uuid` means a unique server ID assigned exclusively to it. To check the ID, go to the server's website and copy the -last element of the website address. For example, if it looks like -this: https://lista-minecraft.pl/serwery/minecraft/183413bc-4588-4265-8f06-346963e5d7df - the ID will -be `183413bc-4588-4265-8f06-346963e5d7df`. +## Documentation -`reward-commands` is a list of commands that will be sent to the server console after the player's vote has been -successfully verified. The following placeholders are available: +| | | +|---|---| +| [Installation](docs/installation.md) | requirements, supported servers, upgrading from 3.x | +| [Configuration](docs/configuration.md) | `settings.yml`, `messages.yml`, commands and permissions | +| [How it works](docs/architecture.md) | API polling, reward rules, code structure | +| [Development](docs/development.md) | building, Docker, test server with a mock API | +| [Testing](docs/testing.md) | running tests, what is covered, writing new ones | +| [Release](docs/release.md) | publishing a new version | -- `%player_name%` - name of the player, -- `%player_display_name%` - display name of the player, -- `%player_uuid%` - unique player ID, -- `%server_name%` - server name, -- `%server_address%` - server page address. +## Quick start -If the plugin has been configured correctly, after voting, the player can use the `/votereward` command to receive the -vote reward. \ No newline at end of file +1. Download `VoteReward-.jar` from [Releases](https://github.com/dudekm/VoteReward/releases/latest) and put it in `plugins/`. +2. Start the server, then in `plugins/VoteReward/settings.yml` enter your server's `uuid` from each list and the reward commands. +3. Run `/votereward reload`. diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 0000000..592aeac --- /dev/null +++ b/compose.yaml @@ -0,0 +1,53 @@ +# Local development. See docs/development.md. +# +# docker compose run --rm build # tests + jar, copied to docker/plugins/ +# docker compose up -d minecraft # test server with the plugin + mock vote list +# docker compose logs -f minecraft +# +# Server type and version: MC_TYPE (PAPER, SPIGOT, PURPUR, FOLIA…), MC_VERSION (1.18.2 … 26.3), +# MC_JAVA — the image's Java tag: java17 for 1.18–1.20.4, java21 for 1.20.5–1.21.x, java25 for 26.x. +# MC_TYPE=SPIGOT MC_VERSION=1.18.2 MC_JAVA=java17 docker compose up -d minecraft + +services: + build: + build: . + volumes: + - ./:/workspace + - maven-cache:/root/.m2 + command: > + sh -c "mvn -B verify && cp target/VoteReward-*.jar docker/plugins/VoteReward.jar" + + # Imitates GET /api/v1/servers/{uuid}/votes of the vote lists. + # Edit docker/mock-api/mappings/votes.json, then: curl -X POST localhost:8089/__admin/mappings/reset + mock-api: + image: wiremock/wiremock:3.13.1 + command: ["--global-response-templating", "--verbose"] + ports: + - "8089:8080" + volumes: + - ./docker/mock-api:/home/wiremock + + minecraft: + image: itzg/minecraft-server:${MC_JAVA:-java25} + depends_on: + - mock-api + environment: + EULA: "TRUE" + TYPE: ${MC_TYPE:-PAPER} + VERSION: ${MC_VERSION:-LATEST} + # Lets you join under the nickname from the mock vote (DevPlayer) without a Mojang account. + ONLINE_MODE: "FALSE" + MEMORY: 2G + # Copies docker/plugins (the jar and settings.yml pointing at the mock) into the server. + COPY_PLUGINS_SRC: /plugins + ports: + - "25565:25565" + volumes: + - ./docker/plugins:/plugins:ro + - minecraft-data:/data + stdin_open: true + tty: true + +volumes: + maven-cache: + minecraft-data: diff --git a/dependency-reduced-pom.xml b/dependency-reduced-pom.xml deleted file mode 100644 index 5a85aa4..0000000 --- a/dependency-reduced-pom.xml +++ /dev/null @@ -1,56 +0,0 @@ - - - 4.0.0 - me.adixe - VoteReward - 3.2.0 - - - - maven-shade-plugin - 3.5.1 - - - package - - shade - - - - - - - org.bstats - shaded.org.bstats - - - - - - - - - spigot-repo - https://hub.spigotmc.org/nexus/content/repositories/snapshots/ - - - - - org.spigotmc - spigot-api - 1.18.2-R0.1-SNAPSHOT - provided - - - com.squareup.okhttp3 - okhttp - 4.12.0 - provided - - - - 17 - 17 - UTF-8 - - diff --git a/docker/mock-api/mappings/votes.json b/docker/mock-api/mappings/votes.json new file mode 100644 index 0000000..138c58c --- /dev/null +++ b/docker/mock-api/mappings/votes.json @@ -0,0 +1,31 @@ +{ + "request": { + "method": "GET", + "urlPathPattern": "/api/v1/servers/[0-9a-fA-F-]+/votes" + }, + "response": { + "status": 200, + "headers": { + "Content-Type": "application/ld+json; charset=utf-8" + }, + "jsonBody": { + "@context": "/api/v1/contexts/Vote", + "@id": "/api/v1/servers/00000000-0000-0000-0000-000000000000/votes", + "@type": "Collection", + "totalItems": 1, + "member": [ + { + "@id": "/api/v1/votes/7d4c3f8e-0000-4000-8000-000000000001", + "@type": "Vote", + "uuid": "7d4c3f8e-0000-4000-8000-000000000001", + "nickname": "DevPlayer", + "createdAt": "{{now}}" + } + ], + "view": { + "@id": "/api/v1/servers/00000000-0000-0000-0000-000000000000/votes", + "@type": "PartialCollectionView" + } + } + } +} diff --git a/docker/plugins/VoteReward/settings.yml b/docker/plugins/VoteReward/settings.yml new file mode 100644 index 0000000..bfba78c --- /dev/null +++ b/docker/plugins/VoteReward/settings.yml @@ -0,0 +1,11 @@ +# Development settings: the "mock" list is the WireMock container from compose.yaml. +polling: + interval: 10s + +servers: + mock: + address: http://mock-api:8080 + uuid: 183413bc-4588-4265-8f06-346963e5d7df + reward-commands: + - give %player_name% diamond + - say %player_name% voted on %server_name% diff --git a/docs/architecture.md b/docs/architecture.md new file mode 100644 index 0000000..640da5c --- /dev/null +++ b/docs/architecture.md @@ -0,0 +1,65 @@ +# How it works + +[← Contents](../README.md) · [Polski](pl/architecture.md) + +## Flow + +``` +every polling.interval (async thread) + └─ VotePoller: for each list in settings.yml + ├─ VoteLedger.checkFrom() → where to query from + ├─ ListApiVoteSource → GET /api/v1/servers/{uuid}/votes?createdAt[after]=… + ├─ VoteLedger.record() → new votes → pending rewards + └─ RewardService.rewardsEarned()→ online players get rewards right away +player join → RewardService.deliver() → pending rewards +/votereward → RewardService.deliver() +``` + +## Polling the API + +Endpoint: `GET {address}/api/v1/servers/{uuid}/votes` (API Platform, JSON-LD format). + +Parameters sent by the plugin: + +- `createdAt[after]=` — only votes since the given moment, +- `order[createdAt]=asc` — oldest first, so pages can be read in order. + +Further pages are fetched from `view.next` (max. 20 pages per check; the rest is fetched by the next +check, since it starts from the last vote read). Links to a different domain are ignored. + +Where to query from: + +- first check of a list: the last **1 hour**, +- subsequent checks: from the previous check **minus a 5-minute overlap** — a vote saved with a slight delay + or affected by clock skew won't be lost; votes read twice are recognised by their `uuid`, +- after a longer break (e.g. the server was offline): at most **24 hours** back. + +In practice each request covers a few minutes, so the load on the list is minimal. +A list that doesn't respond is logged once (and once when it comes back), not every 30 seconds. + +## State (`data/ledger.yml`) + +`VoteLedger` remembers: the read position for each list, who has been rewarded on a given day, and +rewards waiting for players. It is saved after every change (written to a temporary file and swapped in — +a crash mid-write doesn't corrupt the file). + +## Code structure + +Packages with no Bukkit dependency (unit tested): + +| Package | Contents | +|---|---| +| `vote` | Value Objects: `ServerId`, `Nickname`, `Vote`, `VoteDay` | +| `site` | list configuration: `VoteSite`, `ListAddress`, `RewardCommand` | +| `config` | `Settings`, `SettingsParser`, `Durations` | +| `api` | list API client: `ListApiVoteSource`, `VotePageParser`, `HttpTransport` | +| `ledger` | `VoteLedger` (reward rules), `YamlLedgerRepository` | +| `reward` | `VotePoller`, `RewardService` and the `RewardDispatcher`, `PlayerDirectory` ports | + +Server layer — the `bukkit` package and the `VoteReward` class (entry point that wires everything together): +command, join listener, reward dispatching, messages, and `TaskScheduler` with two implementations +(Bukkit, and Folia via reflection — the Folia API is not part of the Spigot API). + +Dependencies point one way: `bukkit` → logic, never the reverse. The logic talks to the outside world through +interfaces (`VoteSource`, `HttpTransport`, `LedgerRepository`, `RewardDispatcher`, `PlayerDirectory`, +`ConfigView`), so tests can plug in simple fakes. diff --git a/docs/configuration.md b/docs/configuration.md new file mode 100644 index 0000000..a5fd003 --- /dev/null +++ b/docs/configuration.md @@ -0,0 +1,76 @@ +# Configuration + +[← Contents](../README.md) · [Polski](pl/configuration.md) + +The files are in `plugins/VoteReward/`. After making changes: `/votereward reload`. + +## settings.yml + +```yaml +polling: + interval: 30s + +servers: + lista-minecraft: + address: https://lista-minecraft.pl + uuid: 183413bc-4588-4265-8f06-346963e5d7df + reward-commands: + - xp add %player_name% 100 + - give %player_name% diamond +``` + +### `polling.interval` + +How often the plugin checks each list for new votes. Format: `30s`, `1m`, `2m30s` or a plain number of seconds. +Default **30s**, minimum **10s** (a lower value is raised and a warning is printed to the console). + +Each check fetches **only the votes since the previous check** (the `createdAt[after]` filter), +not the whole history — see [how it works](architecture.md#polling-the-api). + +### `servers` + +The lists your server is on. The key names (`lista-minecraft` etc.) are arbitrary but must be unique +— they appear in messages as `%server_name%`. + +| Key | Description | +|---|---| +| `address` | the list's website address, e.g. `https://lista-minecraft.pl` | +| `uuid` | your server's ID on the list — the last part of the server page URL, e.g. `…/serwery/minecraft/183413bc-4588-4265-8f06-346963e5d7df` | +| `reward-commands` | commands run from the console for each vote (without `/`) | + +An invalid entry (bad address, missing `uuid`) is skipped with a warning in the console — the other lists keep working. + +Placeholders in commands: + +| Placeholder | Value | +|---|---| +| `%player_name%` | player's name | +| `%player_display_name%` | player's display name | +| `%player_uuid%` | player's UUID | +| `%server_name%` | list name from `settings.yml` | +| `%server_address%` | list address | + +### Reward rules + +- A player gets a reward **once a day per list** (the day is counted in UTC — the same way the lists count it). +- If the player is online, the reward is given as soon as the vote is detected. +- If they are offline, they get it the next time they join the server. +- An unclaimed reward expires after 7 days. +- A vote cast without a nickname gives no reward. + +## messages.yml + +Colours use the `&` format (`&a` green, `&c` red, `&e` yellow, `&l` bold…). +An empty message (`''`) is not sent. Missing keys are taken from the default file in the `.jar`. + +## Commands and permissions + +Command: `/votereward` (alias `/vr`). + +| Command | Permission | Default | Description | +|---|---|---|---| +| `/vr` or `/vr reward` | `votereward.reward` | everyone | claims pending rewards | +| `/vr check` | `votereward.check` | everyone | today's vote status on each list | +| `/vr check ` | `votereward.check.others` | OP | another player's status | +| `/vr reload` | `votereward.reload` | OP | reloads both files and the interval | +| `/vr poll` | `votereward.poll` | OP | checks the lists immediately (e.g. for testing) | diff --git a/docs/development.md b/docs/development.md new file mode 100644 index 0000000..28b2ca0 --- /dev/null +++ b/docs/development.md @@ -0,0 +1,77 @@ +# Development + +[← Contents](../README.md) · [Polski](pl/development.md) + +## Requirements + +- **Docker** with Compose — enough for everything below, or +- **JDK 17+** and **Maven 3.9+**, if you prefer to build without Docker. + +## Building + +```bash +# In Docker: tests + jar (also copied to docker/plugins/ for the test server) +docker compose run --rm build + +# Locally +mvn verify +``` + +Output: `target/VoteReward-.jar` (the `original-…jar` file is the version without bundled libraries — ignore it). + +## Test server with a mock API + +`compose.yaml` starts: + +- `mock-api` — WireMock imitating `GET /api/v1/servers/{uuid}/votes`; returns a single vote from player + **DevPlayer** with the current date (`docker/mock-api/mappings/votes.json`), +- `minecraft` — an [itzg/minecraft-server](https://docker-minecraft-server.readthedocs.io/) server + with the plugin and a `settings.yml` pointing at the mock (`docker/plugins/VoteReward/settings.yml`, checks every 10 s). + +```bash +docker compose run --rm build # build the jar +docker compose up -d minecraft # server + mock API +docker compose logs -f minecraft # console +docker compose attach minecraft # interactive console (detach: Ctrl+P, Ctrl+Q) +``` + +Connect to `localhost:25565` as **DevPlayer** (the server runs in offline mode, so no Mojang account is +needed). Within 10 s you'll receive a diamond. + +### Different server software or version + +```bash +MC_TYPE=SPIGOT MC_VERSION=1.18.2 MC_JAVA=java17 docker compose up -d minecraft +MC_TYPE=PAPER MC_VERSION=1.21.4 MC_JAVA=java21 docker compose up -d minecraft +MC_TYPE=FOLIA MC_VERSION=1.21.4 MC_JAVA=java21 docker compose up -d minecraft +MC_TYPE=PAPER MC_VERSION=26.3 MC_JAVA=java25 docker compose up -d minecraft +``` + +| Minecraft version | `MC_JAVA` | +|---|---| +| 1.18 – 1.20.4 | `java17` | +| 1.20.5 – 1.21.x | `java21` | +| 26.x | `java25` | + +When switching versions, delete the world to avoid conversion: `docker compose down -v`. + +### Mock API + +- Change the nickname or add votes in `docker/mock-api/mappings/votes.json`, then reload: + `curl -X POST localhost:8089/__admin/mappings/reset`. +- Preview the response: `curl 'localhost:8089/api/v1/servers/183413bc-4588-4265-8f06-346963e5d7df/votes'`. +- The same player is rewarded once per UTC day. To test again: stop the server and delete + `plugins/VoteReward/data/ledger.yml` from the volume (`docker compose down -v` wipes everything). + +### A real list instead of the mock + +In `docker/plugins/VoteReward/settings.yml` set `address` to the list's address (or a locally running +list application, e.g. `http://host.docker.internal:8080`) and a real `uuid`. + +## Conventions + +- Domain logic doesn't import `org.bukkit` — everything that touches the server lives in the `bukkit` package. +- Java 17 (the oldest required by the supported Minecraft versions) — no APIs from newer JDKs. +- Server API: only methods present in Spigot 1.18.2 and not removed up to 26.3 (compilation targets 1.18.2). +- New configuration value → default in code, entry in `settings.yml`, test in `SettingsParserTest` + and a description in [configuration](configuration.md). diff --git a/docs/installation.md b/docs/installation.md new file mode 100644 index 0000000..f6016f2 --- /dev/null +++ b/docs/installation.md @@ -0,0 +1,49 @@ +# Installation + +[← Contents](../README.md) · [Polski](pl/installation.md) + +## Requirements + +- A Minecraft **1.18 – 26.3** server based on the Bukkit API (see below). +- **Java 17 or newer** — in practice whatever your Minecraft version already requires + (1.18–1.20.4: Java 17, 1.20.5–1.21.x: Java 21, 26.x: Java 25). +- Outbound internet access (HTTPS) to the addresses of the lists your server is on. + +The plugin needs no additional libraries or plugins. + +## Supported servers + +| Software | Support | Notes | +|---|---|---| +| Spigot / CraftBukkit | ✅ | | +| Paper and forks (Purpur, Pufferfish…) | ✅ | | +| Folia | ✅ | detected automatically, uses region schedulers | +| Hybrids (Mohist, Arclight…) | ⚠️ | should work since they load Bukkit plugins — untested | +| Vanilla (Mojang's server) | ❌ | vanilla doesn't load plugins — use e.g. Paper (a drop-in replacement for vanilla) | +| Fabric / NeoForge / Sponge | ❌ | different modding APIs; out of scope for this plugin | + +The plugin is compiled against the oldest supported API (Spigot 1.18.2) and only uses methods +available in all versions up to 26.3, so **a single `.jar` works on every version**. + +## Step-by-step installation + +1. Download the latest `VoteReward-.jar` from + [Releases](https://github.com/dudekm/VoteReward/releases/latest). +2. Put the file in the server's `plugins/` folder and start (restart) the server. +3. A `plugins/VoteReward/` folder is created with `settings.yml` and `messages.yml`. +4. In `settings.yml`, under `servers`, set your server's `uuid` on each list and the reward commands + — see [configuration](configuration.md). +5. Run `/votereward reload` (or restart the server). The console will show + `Checking N vote list(s) every 30s.` + +## Upgrading from 3.x + +- A 3.x `settings.yml` works unchanged (the `servers` section has the same format). + A missing `polling.interval` defaults to `30s`. +- **Rewards are now given automatically** — players no longer have to type `/votereward` after voting. + The command still exists and claims any pending rewards. +- `messages.yml` has new keys and uses `&` colour codes (instead of ``). The simplest option is to delete + the old file — a new one is created on startup. Missing keys are taken from the default file in the `.jar` anyway. +- The 3.x `data/votes.yml` file is no longer used and can be deleted; the new data lives in `data/ledger.yml`. +- `votereward.check` is now available to players by default (viewing their own votes); + viewing other players requires `votereward.check.others`. diff --git a/docs/pl/architecture.md b/docs/pl/architecture.md new file mode 100644 index 0000000..cb49313 --- /dev/null +++ b/docs/pl/architecture.md @@ -0,0 +1,65 @@ +# Jak to działa + +[← Spis treści](../../README-PL.md) · [English](../architecture.md) + +## Przepływ + +``` +co polling.interval (wątek asynchroniczny) + └─ VotePoller: dla każdej listy z settings.yml + ├─ VoteLedger.checkFrom() → od kiedy pytać + ├─ ListApiVoteSource → GET /api/v1/servers/{uuid}/votes?createdAt[after]=… + ├─ VoteLedger.record() → nowe głosy → nagrody oczekujące + └─ RewardService.rewardsEarned()→ gracze online dostają nagrody od razu +wejście gracza → RewardService.deliver() → zaległe nagrody +/votereward → RewardService.deliver() +``` + +## Odpytywanie API + +Endpoint: `GET {address}/api/v1/servers/{uuid}/votes` (API Platform, format JSON-LD). + +Parametry wysyłane przez plugin: + +- `createdAt[after]=` — tylko głosy od podanego momentu, +- `order[createdAt]=asc` — od najstarszego, żeby strony dało się czytać po kolei. + +Kolejne strony są pobierane z `view.next` (maks. 20 stron na sprawdzenie; resztę pobierze następne +sprawdzenie, bo zacznie od ostatniego przeczytanego głosu). Linki do innej domeny są ignorowane. + +Od kiedy pytać: + +- pierwsze sprawdzenie listy: ostatnia **1 godzina**, +- kolejne: od poprzedniego sprawdzenia **minus 5 minut zakładki** — głos zapisany z lekkim opóźnieniem + lub przy różnicy zegarów nie przepadnie; głosy przeczytane drugi raz są rozpoznawane po `uuid`, +- po dłuższej przerwie (np. serwer był wyłączony): maks. **24 godziny** wstecz. + +W praktyce każde zapytanie obejmuje kilka minut, więc obciążenie listy jest minimalne. +Lista, która nie odpowiada, jest logowana raz (i raz po powrocie), a nie co 30 sekund. + +## Stan (`data/ledger.yml`) + +`VoteLedger` pamięta: pozycję odczytu każdej listy, kto dostał nagrodę danego dnia oraz nagrody +czekające na graczy. Zapisywany po każdej zmianie (zapis do pliku tymczasowego i podmiana — +awaria w trakcie zapisu nie psuje pliku). + +## Struktura kodu + +Pakiety bez zależności od Bukkita (testowane jednostkowo): + +| Pakiet | Zawartość | +|---|---| +| `vote` | Value Objecty: `ServerId`, `Nickname`, `Vote`, `VoteDay` | +| `site` | konfiguracja listy: `VoteSite`, `ListAddress`, `RewardCommand` | +| `config` | `Settings`, `SettingsParser`, `Durations` | +| `api` | klient API list: `ListApiVoteSource`, `VotePageParser`, `HttpTransport` | +| `ledger` | `VoteLedger` (zasady nagród), `YamlLedgerRepository` | +| `reward` | `VotePoller`, `RewardService` i porty `RewardDispatcher`, `PlayerDirectory` | + +Warstwa serwera — pakiet `bukkit` i klasa `VoteReward` (punkt wejścia, składa wszystko w całość): +komenda, listener wejścia, wydawanie nagród, wiadomości oraz `TaskScheduler` z dwiema implementacjami +(Bukkit oraz Folia przez refleksję — API Folii nie jest częścią Spigot API). + +Zależności idą w jedną stronę: `bukkit` → logika, nigdy odwrotnie. Logika rozmawia ze światem przez +interfejsy (`VoteSource`, `HttpTransport`, `LedgerRepository`, `RewardDispatcher`, `PlayerDirectory`, +`ConfigView`), więc w testach podstawia się proste atrapy. diff --git a/docs/pl/configuration.md b/docs/pl/configuration.md new file mode 100644 index 0000000..8b59a96 --- /dev/null +++ b/docs/pl/configuration.md @@ -0,0 +1,76 @@ +# Konfiguracja + +[← Spis treści](../../README-PL.md) · [English](../configuration.md) + +Pliki są w `plugins/VoteReward/`. Po zmianach: `/votereward reload`. + +## settings.yml + +```yaml +polling: + interval: 30s + +servers: + lista-minecraft: + address: https://lista-minecraft.pl + uuid: 183413bc-4588-4265-8f06-346963e5d7df + reward-commands: + - xp add %player_name% 100 + - give %player_name% diamond +``` + +### `polling.interval` + +Jak często plugin sprawdza nowe głosy na każdej liście. Format: `30s`, `1m`, `2m30s` albo sama liczba sekund. +Domyślnie **30s**, minimum **10s** (niższa wartość zostanie podniesiona, a w konsoli pojawi się ostrzeżenie). + +Każde sprawdzenie pobiera **tylko głosy od poprzedniego sprawdzenia** (filtr `createdAt[after]`), +a nie całą historię — patrz [jak to działa](architecture.md#odpytywanie-api). + +### `servers` + +Listy, na których jest serwer. Nazwy kluczy (`lista-minecraft` itd.) są dowolne, ale muszą być unikalne +— pojawiają się w wiadomościach jako `%server_name%`. + +| Klucz | Opis | +|---|---| +| `address` | adres strony listy, np. `https://lista-minecraft.pl` | +| `uuid` | ID serwera na liście — ostatni fragment adresu strony serwera, np. `…/serwery/minecraft/183413bc-4588-4265-8f06-346963e5d7df` | +| `reward-commands` | komendy wykonywane z konsoli za każdy głos (bez `/`) | + +Błędny wpis (zły adres, brak `uuid`) jest pomijany z ostrzeżeniem w konsoli — pozostałe listy działają dalej. + +Placeholdery w komendach: + +| Placeholder | Wartość | +|---|---| +| `%player_name%` | nick gracza | +| `%player_display_name%` | wyświetlana nazwa gracza | +| `%player_uuid%` | UUID gracza | +| `%server_name%` | nazwa listy z `settings.yml` | +| `%server_address%` | adres listy | + +### Zasady nagradzania + +- Gracz dostaje nagrodę **raz dziennie za każdą listę** (dzień liczony w UTC — tak jak liczą go listy). +- Jeśli gracz jest online, nagroda jest wydawana od razu po wykryciu głosu. +- Jeśli jest offline — dostaje ją przy najbliższym wejściu na serwer. +- Nieodebrana nagroda przepada po 7 dniach. +- Głos oddany bez nicku nie daje nagrody. + +## messages.yml + +Kolory w formacie `&` (`&a` zielony, `&c` czerwony, `&e` żółty, `&l` pogrubienie…). +Pusta wiadomość (`''`) nie jest wysyłana. Brakujące klucze są brane z domyślnego pliku w `.jar`. + +## Komendy i uprawnienia + +Komenda: `/votereward` (alias `/vr`). + +| Komenda | Uprawnienie | Domyślnie | Opis | +|---|---|---|---| +| `/vr` lub `/vr reward` | `votereward.reward` | wszyscy | odbiera zaległe nagrody | +| `/vr check` | `votereward.check` | wszyscy | dzisiejszy status głosów na każdej liście | +| `/vr check ` | `votereward.check.others` | OP | status innego gracza | +| `/vr reload` | `votereward.reload` | OP | przeładowuje oba pliki i interwał | +| `/vr poll` | `votereward.poll` | OP | sprawdza listy natychmiast (np. do testów) | diff --git a/docs/pl/development.md b/docs/pl/development.md new file mode 100644 index 0000000..2169c0e --- /dev/null +++ b/docs/pl/development.md @@ -0,0 +1,77 @@ +# Development + +[← Spis treści](../../README-PL.md) · [English](../development.md) + +## Wymagania + +- **Docker** z Compose — wystarczy do wszystkiego poniżej, albo +- **JDK 17+** i **Maven 3.9+**, jeśli wolisz budować bez Dockera. + +## Budowanie + +```bash +# W Dockerze: testy + jar (kopiowany też do docker/plugins/ dla serwera testowego) +docker compose run --rm build + +# Lokalnie +mvn verify +``` + +Wynik: `target/VoteReward-.jar` (plik `original-…jar` to wersja bez dołączonych bibliotek — pomiń go). + +## Serwer testowy z atrapą API + +`compose.yaml` uruchamia: + +- `mock-api` — WireMock udający `GET /api/v1/servers/{uuid}/votes`; zwraca jeden głos gracza + **DevPlayer** z bieżącą datą (`docker/mock-api/mappings/votes.json`), +- `minecraft` — serwer [itzg/minecraft-server](https://docker-minecraft-server.readthedocs.io/) + z pluginem i `settings.yml` wskazującym na atrapę (`docker/plugins/VoteReward/settings.yml`, sprawdzanie co 10 s). + +```bash +docker compose run --rm build # zbuduj jar +docker compose up -d minecraft # serwer + atrapa API +docker compose logs -f minecraft # konsola +docker compose attach minecraft # konsola interaktywna (wyjście: Ctrl+P, Ctrl+Q) +``` + +Połącz się z `localhost:25565` jako **DevPlayer** (serwer działa w trybie offline, więc konto Mojang nie jest +potrzebne). Po maks. 10 s dostaniesz diament. + +### Inny silnik lub wersja + +```bash +MC_TYPE=SPIGOT MC_VERSION=1.18.2 MC_JAVA=java17 docker compose up -d minecraft +MC_TYPE=PAPER MC_VERSION=1.21.4 MC_JAVA=java21 docker compose up -d minecraft +MC_TYPE=FOLIA MC_VERSION=1.21.4 MC_JAVA=java21 docker compose up -d minecraft +MC_TYPE=PAPER MC_VERSION=26.3 MC_JAVA=java25 docker compose up -d minecraft +``` + +| Wersja Minecrafta | `MC_JAVA` | +|---|---| +| 1.18 – 1.20.4 | `java17` | +| 1.20.5 – 1.21.x | `java21` | +| 26.x | `java25` | + +Przy zmianie wersji usuń świat, żeby uniknąć konwersji: `docker compose down -v`. + +### Atrapa API + +- Zmień nick lub dodaj głosy w `docker/mock-api/mappings/votes.json`, potem przeładuj: + `curl -X POST localhost:8089/__admin/mappings/reset`. +- Podgląd odpowiedzi: `curl 'localhost:8089/api/v1/servers/183413bc-4588-4265-8f06-346963e5d7df/votes'`. +- Ten sam gracz dostaje nagrodę raz na dzień UTC. Żeby przetestować ponownie: zatrzymaj serwer i usuń + `plugins/VoteReward/data/ledger.yml` z wolumenu (`docker compose down -v` czyści wszystko). + +### Prawdziwa lista zamiast atrapy + +W `docker/plugins/VoteReward/settings.yml` ustaw `address` na adres listy (lub lokalnie uruchomionej +aplikacji listy, np. `http://host.docker.internal:8080`) i prawdziwe `uuid`. + +## Konwencje + +- Logika domenowa nie importuje `org.bukkit` — wszystko, co dotyka serwera, jest w pakiecie `bukkit`. +- Java 17 (najstarsza wymagana przez wspierane wersje Minecrafta) — bez API z nowszych JDK. +- API serwera: tylko metody obecne w Spigot 1.18.2 i nieusunięte do 26.3 (kompilacja odbywa się na 1.18.2). +- Nowa wartość konfiguracji → domyślna wartość w kodzie, wpis w `settings.yml`, test w `SettingsParserTest` + i opis w [konfiguracji](configuration.md). diff --git a/docs/pl/installation.md b/docs/pl/installation.md new file mode 100644 index 0000000..f40e649 --- /dev/null +++ b/docs/pl/installation.md @@ -0,0 +1,49 @@ +# Instalacja + +[← Spis treści](../../README-PL.md) · [English](../installation.md) + +## Wymagania + +- Serwer Minecraft **1.18 – 26.3** oparty na Bukkit API (zob. niżej). +- **Java 17 lub nowsza** — w praktyce taka, jakiej i tak wymaga wersja Minecrafta + (1.18–1.20.4: Java 17, 1.20.5–1.21.x: Java 21, 26.x: Java 25). +- Wyjście do internetu (HTTPS) do adresów list, na których jest serwer. + +Plugin nie potrzebuje żadnych dodatkowych bibliotek ani pluginów. + +## Obsługiwane serwery + +| Silnik | Wsparcie | Uwagi | +|---|---|---| +| Spigot / CraftBukkit | ✅ | | +| Paper i forki (Purpur, Pufferfish…) | ✅ | | +| Folia | ✅ | wykrywana automatycznie, używa schedulerów regionów | +| Hybrydy (Mohist, Arclight…) | ⚠️ | powinny działać, bo ładują pluginy Bukkit — nietestowane | +| Vanilla (serwer od Mojang) | ❌ | vanilla nie ładuje pluginów — trzeba użyć np. Paper (drop-in zamiennik vanilli) | +| Fabric / NeoForge / Sponge | ❌ | inne API modów; poza zakresem tego pluginu | + +Plugin jest kompilowany na najstarszym wspieranym API (Spigot 1.18.2) i używa wyłącznie metod +dostępnych we wszystkich wersjach do 26.3, więc **jeden plik `.jar` działa na każdej wersji**. + +## Instalacja krok po kroku + +1. Pobierz najnowszy `VoteReward-.jar` z + [Releases](https://github.com/dudekm/VoteReward/releases/latest). +2. Wrzuć plik do folderu `plugins/` serwera i uruchom (zrestartuj) serwer. +3. Powstanie folder `plugins/VoteReward/` z plikami `settings.yml` i `messages.yml`. +4. W `settings.yml` w sekcji `servers` ustaw `uuid` swojego serwera na każdej liście i komendy nagród + — opis w [konfiguracji](configuration.md). +5. Wpisz `/votereward reload` (albo zrestartuj serwer). W konsoli pojawi się + `Checking N vote list(s) every 30s.` + +## Aktualizacja z wersji 3.x + +- `settings.yml` z 3.x działa bez zmian (sekcja `servers` ma ten sam format). + Brakujące `polling.interval` przyjmuje domyślnie `30s`. +- **Nagrody są teraz przyznawane automatycznie** — gracz nie musi wpisywać `/votereward` po głosowaniu. + Komenda nadal istnieje i odbiera ewentualne zaległe nagrody. +- `messages.yml` ma nowe klucze i kolory w formacie `&` (zamiast ``). Najprościej usunąć stary plik — + przy starcie powstanie nowy. Brakujące klucze i tak biorą się z domyślnego pliku w `.jar`. +- Plik `data/votes.yml` z 3.x nie jest już używany i można go usunąć; nowe dane są w `data/ledger.yml`. +- `votereward.check` jest teraz domyślnie dostępne dla graczy (podgląd własnych głosów); + podgląd innych graczy wymaga `votereward.check.others`. diff --git a/docs/pl/release.md b/docs/pl/release.md new file mode 100644 index 0000000..058bd61 --- /dev/null +++ b/docs/pl/release.md @@ -0,0 +1,25 @@ +# Release + +[← Spis treści](../../README-PL.md) · [English](../release.md) + +Wersjonowanie: [SemVer](https://semver.org/lang/pl/) — `MAJOR` przy niekompatybilnych zmianach konfiguracji +lub zachowania, `MINOR` przy nowych funkcjach, `PATCH` przy poprawkach. + +## Kroki + +1. Ustaw wersję w `pom.xml` (``). `plugin.yml` bierze ją automatycznie z Mavena. +2. Zbuduj i przetestuj: + ```bash + mvn clean verify # albo: docker compose run --rm build + ``` +3. Wykonaj [testy ręczne](testing.md#testy-ręczne-przed-wydaniem). +4. Commit, tag i push: + ```bash + git commit -am "Release 4.0.0" + git tag v4.0.0 + git push origin main --tags + ``` +5. Na GitHubie: **Releases → Draft a new release**, wybierz tag, dodaj opis zmian + (przy wersji MAJOR — sekcję o aktualizacji, jak w [instalacji](installation.md#aktualizacja-z-wersji-3x)) + i załącz `target/VoteReward-.jar` (nie `original-…jar`). +6. Opcjonalnie: zaktualizuj stronę pluginu na SpigotMC. diff --git a/docs/pl/testing.md b/docs/pl/testing.md new file mode 100644 index 0000000..489f8e3 --- /dev/null +++ b/docs/pl/testing.md @@ -0,0 +1,53 @@ +# Testy + +[← Spis treści](../../README-PL.md) · [English](../testing.md) + +## Uruchamianie + +```bash +mvn test # wszystkie testy +mvn test -Dtest=VoteLedgerTest # jedna klasa +mvn test -Dtest='VoteLedgerTest#nextUtcDayEarnsAgain' +docker compose run --rm build # to samo w Dockerze (mvn verify) +``` + +Testy używają JUnit 5 i nie potrzebują serwera Minecraft ani internetu. + +## CI + +GitHub Actions (`.github/workflows/tests.yml`) uruchamia `mvn -B verify` na Javie 17, 21 i 25 przy każdym pull requeście +i każdym pushu na branch inny niż `main`. Przy niepowodzeniu raporty testów są dołączane do przebiegu jako artefakt. + +## Co jest testowane + +| Obszar | Testy | +|---|---| +| Value Objecty | `NicknameTest`, `ServerIdTest`, `VoteTest`, `ListAddressTest`, `RewardCommandTest`, `PlaceholdersTest` | +| Konfiguracja | `SettingsParserTest` (w tym zgodność z plikami 3.x), `DurationsTest` | +| API list | `VotePageParserTest` (JSON-LD, `hydra:`, zwykły JSON, błędne dane), `ListApiVoteSourceTest` (parametry zapytania, paginacja, błędy HTTP), `ListApiVoteSourceIntegrationTest` (prawdziwe HTTP na lokalnym serwerze) | +| Zasady nagród | `VoteLedgerTest` (kursor, zakładka, raz dziennie, deduplikacja, wygasanie), `RewardServiceTest`, `VotePollerTest` | +| Zapis stanu | `YamlLedgerRepositoryTest` | + +Warstwa `bukkit` jest celowo cienka (wywołania API serwera) i sprawdzana ręcznie na serwerze testowym +z [developmentu](development.md#serwer-testowy-z-atrapą-api). + +## Pisanie testów + +- Zależności zewnętrzne zastępuj prostymi atrapami interfejsów (`FakeHttpTransport`, `MapConfigView`, + lambdy dla `RewardDispatcher`/`PlayerDirectory`) — bez bibliotek do mockowania. +- Czas: wstrzykuj `Clock` / podawaj `Instant` jawnie, nigdy `Instant.now()` w asercjach. +- Wspólne dane testowe: `TestData` (lista, głos i strona w formacie API). + +## Testy ręczne przed wydaniem + +Na serwerze z `compose.yaml` (patrz [development](development.md)) sprawdź co najmniej: + +| Silnik | Wersja | +|---|---| +| Spigot | 1.18.2 | +| Paper | najnowsza 1.21.x | +| Folia | najnowsza dostępna | +| Paper | 26.3 | + +Scenariusze: nagroda dla gracza online, nagroda po wejściu (głos oddany offline), `/vr check`, +`/vr reload` ze zmianą `polling.interval`, lista niedostępna (zatrzymaj `mock-api`) i jej powrót. diff --git a/docs/release.md b/docs/release.md new file mode 100644 index 0000000..65fff8d --- /dev/null +++ b/docs/release.md @@ -0,0 +1,25 @@ +# Release + +[← Contents](../README.md) · [Polski](pl/release.md) + +Versioning: [SemVer](https://semver.org/) — `MAJOR` for incompatible configuration or behaviour changes, +`MINOR` for new features, `PATCH` for fixes. + +## Steps + +1. Set the version in `pom.xml` (``). `plugin.yml` picks it up from Maven automatically. +2. Build and test: + ```bash + mvn clean verify # or: docker compose run --rm build + ``` +3. Run the [manual tests](testing.md#manual-tests-before-a-release). +4. Commit, tag and push: + ```bash + git commit -am "Release 4.0.0" + git tag v4.0.0 + git push origin main --tags + ``` +5. On GitHub: **Releases → Draft a new release**, choose the tag, add release notes + (for a MAJOR version — an upgrade section, as in [installation](installation.md#upgrading-from-3x)) + and attach `target/VoteReward-.jar` (not `original-…jar`). +6. Optionally: update the plugin page on SpigotMC. diff --git a/docs/testing.md b/docs/testing.md new file mode 100644 index 0000000..5d035d8 --- /dev/null +++ b/docs/testing.md @@ -0,0 +1,53 @@ +# Testing + +[← Contents](../README.md) · [Polski](pl/testing.md) + +## Running + +```bash +mvn test # all tests +mvn test -Dtest=VoteLedgerTest # a single class +mvn test -Dtest='VoteLedgerTest#nextUtcDayEarnsAgain' +docker compose run --rm build # the same in Docker (mvn verify) +``` + +The tests use JUnit 5 and need neither a Minecraft server nor internet access. + +## CI + +GitHub Actions (`.github/workflows/tests.yml`) runs `mvn -B verify` on Java 17, 21 and 25 for every pull request +and every push to a branch other than `main`. If a run fails, the test reports are attached to it as an artifact. + +## What is tested + +| Area | Tests | +|---|---| +| Value Objects | `NicknameTest`, `ServerIdTest`, `VoteTest`, `ListAddressTest`, `RewardCommandTest`, `PlaceholdersTest` | +| Configuration | `SettingsParserTest` (including compatibility with 3.x files), `DurationsTest` | +| List API | `VotePageParserTest` (JSON-LD, `hydra:`, plain JSON, malformed data), `ListApiVoteSourceTest` (query parameters, pagination, HTTP errors), `ListApiVoteSourceIntegrationTest` (real HTTP against a local server) | +| Reward rules | `VoteLedgerTest` (cursor, overlap, once a day, deduplication, expiry), `RewardServiceTest`, `VotePollerTest` | +| State persistence | `YamlLedgerRepositoryTest` | + +The `bukkit` layer is deliberately thin (server API calls) and is checked manually on the test server +from [development](development.md#test-server-with-a-mock-api). + +## Writing tests + +- Replace external dependencies with simple interface fakes (`FakeHttpTransport`, `MapConfigView`, + lambdas for `RewardDispatcher`/`PlayerDirectory`) — no mocking libraries. +- Time: inject a `Clock` / pass an `Instant` explicitly, never `Instant.now()` in assertions. +- Shared test data: `TestData` (a list, a vote and a page in API format). + +## Manual tests before a release + +On the server from `compose.yaml` (see [development](development.md)) check at least: + +| Software | Version | +|---|---| +| Spigot | 1.18.2 | +| Paper | latest 1.21.x | +| Folia | latest available | +| Paper | 26.3 | + +Scenarios: reward for an online player, reward on join (vote cast while offline), `/vr check`, +`/vr reload` with a changed `polling.interval`, list unavailable (stop `mock-api`) and its recovery. diff --git a/pom.xml b/pom.xml index 0a7a577..86162b1 100644 --- a/pom.xml +++ b/pom.xml @@ -6,40 +6,14 @@ me.adixe VoteReward - 3.2.0 + 4.0.0 - 17 - 17 + + 17 UTF-8 - - - - org.apache.maven.plugins - maven-shade-plugin - 3.5.1 - - - - org.bstats - shaded.org.bstats - - - - - - package - - shade - - - - - - - spigot-repo @@ -48,30 +22,94 @@ + org.spigotmc spigot-api 1.18.2-R0.1-SNAPSHOT provided + - me.adixe - CommonUtilsLib-Spigot - 1.0.0 - compile + com.google.code.gson + gson + 2.8.9 + provided + + + + org.yaml + snakeyaml + 1.30 + provided org.bstats bstats-bukkit - 3.0.2 - compile + 3.1.0 + - com.squareup.okhttp3 - okhttp - 4.12.0 - provided + org.junit.jupiter + junit-jupiter + 5.13.4 + test - \ No newline at end of file + + + VoteReward-${project.version} + + + + src/main/resources + true + + plugin.yml + + + + src/main/resources + + plugin.yml + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.14.0 + + + org.apache.maven.plugins + maven-surefire-plugin + 3.5.3 + + + org.apache.maven.plugins + maven-shade-plugin + 3.6.0 + + false + + + org.bstats + me.adixe.votereward.libs.bstats + + + + + + package + + shade + + + + + + + diff --git a/src/main/java/me/adixe/votereward/VoteReward.java b/src/main/java/me/adixe/votereward/VoteReward.java index 0336c7c..6863abd 100644 --- a/src/main/java/me/adixe/votereward/VoteReward.java +++ b/src/main/java/me/adixe/votereward/VoteReward.java @@ -1,136 +1,241 @@ package me.adixe.votereward; -import me.adixe.commonutilslib.command.CommandService; -import me.adixe.commonutilslib.configuration.Configuration; -import me.adixe.commonutilslib.configuration.SectionHolder; -import me.adixe.commonutilslib.placeholder.PlaceholderManager; -import me.adixe.commonutilslib.placeholder.PlayerProvider; -import me.adixe.commonutilslib.util.MessageUtil; -import me.adixe.votereward.commands.CheckCommand; -import me.adixe.votereward.commands.ReloadCommand; -import me.adixe.votereward.commands.RewardCommand; -import me.adixe.votereward.placeholder.ServerHolderProvider; -import me.adixe.votereward.vote.VoteManager; -import me.adixe.votereward.vote.verifier.LMVerifier; +import me.adixe.votereward.api.JdkHttpTransport; +import me.adixe.votereward.api.ListApiVoteSource; +import me.adixe.votereward.api.VotePageParser; +import me.adixe.votereward.api.VoteSource; +import me.adixe.votereward.bukkit.BukkitConfigView; +import me.adixe.votereward.bukkit.BukkitRewardDispatcher; +import me.adixe.votereward.bukkit.Messages; +import me.adixe.votereward.bukkit.PlayerJoinListener; +import me.adixe.votereward.bukkit.TaskScheduler; +import me.adixe.votereward.bukkit.VoteRewardCommand; +import me.adixe.votereward.config.Durations; +import me.adixe.votereward.config.Settings; +import me.adixe.votereward.config.SettingsParser; +import me.adixe.votereward.ledger.LedgerRepository; +import me.adixe.votereward.ledger.VoteLedger; +import me.adixe.votereward.ledger.YamlLedgerRepository; +import me.adixe.votereward.reward.PollReport; +import me.adixe.votereward.reward.RewardService; +import me.adixe.votereward.reward.VotePoller; +import me.adixe.votereward.site.VoteSite; +import me.adixe.votereward.vote.Nickname; import org.bstats.bukkit.Metrics; import org.bstats.charts.AdvancedPie; +import org.bukkit.Bukkit; +import org.bukkit.command.PluginCommand; +import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.plugin.java.JavaPlugin; -import org.simpleyaml.configuration.file.YamlFile; import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.Reader; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Clock; import java.util.HashMap; +import java.util.HashSet; import java.util.Map; - -public class VoteReward extends JavaPlugin { - private static VoteReward instance; - - private Configuration configuration; - private PlaceholderManager placeholderManager; - private VoteManager voteManager; +import java.util.Set; +import java.util.function.Consumer; +import java.util.logging.Level; + +/** + * Plugin entry point: wires the pieces together and owns their lifecycle. + */ +public final class VoteReward extends JavaPlugin { + private static final int BSTATS_ID = 20120; + + private VoteSource source; + private TaskScheduler scheduler; + private LedgerRepository repository; + private VoteLedger ledger; + + private volatile Settings settings; + private volatile Messages messages; + private volatile RewardService rewards; + private volatile VotePoller poller; @Override public void onEnable() { - instance = this; + scheduler = TaskScheduler.detect(this); + source = new ListApiVoteSource(new JdkHttpTransport(), new VotePageParser(), + "VoteReward/" + getDescription().getVersion()); + repository = new YamlLedgerRepository(getDataFolder().toPath().resolve("data").resolve("ledger.yml")); + + try { + ledger = VoteLedger.restore(repository.load()); + } catch (IOException exception) { + getLogger().log(Level.SEVERE, "Could not read the vote data — starting with an empty one.", exception); + ledger = VoteLedger.empty(); + } - loadConfiguration(); + if (!reload()) { + getLogger().severe("Could not load the configuration — the plugin is disabled."); + getServer().getPluginManager().disablePlugin(this); - loadPlaceholders(); + return; + } - loadCommands(); + PluginCommand command = getCommand("votereward"); + VoteRewardCommand executor = new VoteRewardCommand(this); + command.setExecutor(executor); + command.setTabCompleter(executor); + getServer().getPluginManager().registerEvents(new PlayerJoinListener(this), this); - loadVoteManager(); + startMetrics(); - loadMetrics(); + getLogger().info("Running on " + Bukkit.getName() + " " + Bukkit.getBukkitVersion() + "."); + } - MessageUtil.registerAudiences(this); + @Override + public void onDisable() { + if (scheduler != null) { + scheduler.cancelAll(); + } - getLogger().info("Enabled successfully."); + if (poller != null) { + poller.save(); + } } - private void loadConfiguration() { - configuration = new Configuration(this); - configuration.registerFile("settings.yml", "settings.yml"); - configuration.registerFile("messages.yml", "messages.yml"); - configuration.registerDataFile("data/votes.yml", 10); + /** + * (Re)reads both configuration files and restarts the vote checks with the new settings. + * + * @return false when a file could not be read; the previous configuration then stays active + */ + public synchronized boolean reload() { + Settings newSettings; + Messages newMessages; try { - configuration.reload(); + newSettings = loadSettings(); + newMessages = new Messages(loadYaml("messages.yml", true)); } catch (IOException exception) { - throw new RuntimeException(exception); + getLogger().log(Level.SEVERE, "Could not read the configuration.", exception); + + return false; } - } - private void loadPlaceholders() { - placeholderManager = new PlaceholderManager(); - placeholderManager.register(new PlayerProvider("player")); - placeholderManager.register(new ServerHolderProvider("server")); - } + scheduler.cancelAll(); - private void loadCommands() { - SectionHolder messagesHolder = new SectionHolder( - configuration, "messages", "commands"); + Set siteNames = new HashSet<>(); + newSettings.sites().all().forEach(site -> siteNames.add(site.name())); + ledger.retainSites(siteNames); - CommandService commandService = new CommandService("votereward", - "votereward.command", messagesHolder, false); + settings = newSettings; + messages = newMessages; + rewards = new RewardService(ledger, newSettings.sites(), + nickname -> Bukkit.getPlayerExact(nickname.value()) != null, + new BukkitRewardDispatcher(scheduler, newMessages), getLogger()); + poller = new VotePoller(newSettings, source, ledger, repository, rewards, Clock.systemUTC(), getLogger()); - commandService.register(new RewardCommand("reward", - "votereward.reward", - messagesHolder), "reward"); - commandService.register(new CheckCommand("check", - "votereward.check", - messagesHolder), "check"); - commandService.register(new ReloadCommand("reload", - "votereward.reload", - messagesHolder), "reload"); + VotePoller activePoller = poller; + scheduler.runAsync(activePoller::poll); + scheduler.runAsyncRepeating(activePoller::poll, newSettings.pollInterval()); - commandService.register(this); - } + getLogger().info("Checking " + newSettings.sites().all().size() + " vote list(s) every " + + Durations.format(newSettings.pollInterval()) + "."); - private void loadVoteManager() { - voteManager = new VoteManager(); - voteManager.register(new LMVerifier()); + return true; } - private void loadMetrics() { - Metrics metrics = new Metrics(this, 20120); + /** + * Gives the player whatever is waiting for them. + * + * @return how many rewards were given + */ + public int deliver(Nickname player) { + int delivered = rewards.deliver(player); + + if (delivered > 0) { + VotePoller activePoller = poller; + scheduler.runAsync(activePoller::save); + } - metrics.addCustomChart(new AdvancedPie("siteAddress", () -> { - YamlFile settings = configuration.get("settings"); + return delivered; + } - Map addresses = new HashMap<>(); + /** Checks every list right away instead of waiting for the next scheduled check. */ + public void pollNow(Consumer whenDone) { + VotePoller activePoller = poller; + scheduler.runAsync(() -> { + PollReport report = activePoller.poll(); + scheduler.runSync(() -> whenDone.accept(report)); + }); + } - for (String key : settings.getConfigurationSection("servers").getKeys(false)) { - String address = settings.getString("servers." + key + ".address"); + public Settings settings() { + return settings; + } - addresses.put(address, addresses.getOrDefault(address, 0) + 1); - } + public Messages messages() { + return messages; + } - return addresses; - })); + public VoteLedger ledger() { + return ledger; } - @Override - public void onDisable() { - configuration.save("votes"); + private Settings loadSettings() throws IOException { + SettingsParser.Result result = new SettingsParser().parse(new BukkitConfigView(loadYaml("settings.yml", false))); - MessageUtil.close(); + for (String warning : result.warnings()) { + getLogger().warning("settings.yml: " + warning); + } - getLogger().info("Disabled successfully."); + return result.settings(); } - public static VoteReward getInstance() { - return instance; - } + /** + * Reads a file from the plugin folder, creating it from the jar's copy first. + * + * @param withDefaults whether the jar's copy fills in missing keys — right for messages, wrong for + * settings, where it would bring back the example lists the owner removed + */ + private YamlConfiguration loadYaml(String name, boolean withDefaults) throws IOException { + Path file = getDataFolder().toPath().resolve(name); + + if (!Files.exists(file)) { + saveResource(name, false); + } + + YamlConfiguration configuration = new YamlConfiguration(); + + try (Reader reader = Files.newBufferedReader(file, StandardCharsets.UTF_8)) { + configuration.load(reader); + } catch (org.bukkit.configuration.InvalidConfigurationException exception) { + throw new IOException(name + " is not valid YAML: " + exception.getMessage(), exception); + } + + if (!withDefaults) { + return configuration; + } + + try (InputStream defaults = getResource(name)) { + if (defaults != null) { + configuration.setDefaults(YamlConfiguration.loadConfiguration( + new InputStreamReader(defaults, StandardCharsets.UTF_8))); + } + } - public Configuration getConfiguration() { return configuration; } - public PlaceholderManager getPlaceholderManager() { - return placeholderManager; - } + private void startMetrics() { + Metrics metrics = new Metrics(this, BSTATS_ID); - public VoteManager getVoteManager() { - return voteManager; + metrics.addCustomChart(new AdvancedPie("siteAddress", () -> { + Map addresses = new HashMap<>(); + + for (VoteSite site : settings.sites().all()) { + addresses.merge(site.address().toString(), 1, Integer::sum); + } + + return addresses; + })); } } diff --git a/src/main/java/me/adixe/votereward/api/HttpResult.java b/src/main/java/me/adixe/votereward/api/HttpResult.java new file mode 100644 index 0000000..6d912cd --- /dev/null +++ b/src/main/java/me/adixe/votereward/api/HttpResult.java @@ -0,0 +1,10 @@ +package me.adixe.votereward.api; + +/** + * Status code and body of an HTTP response. + */ +public record HttpResult(int status, String body) { + public boolean isSuccessful() { + return status >= 200 && status < 300; + } +} diff --git a/src/main/java/me/adixe/votereward/api/HttpTransport.java b/src/main/java/me/adixe/votereward/api/HttpTransport.java new file mode 100644 index 0000000..741190f --- /dev/null +++ b/src/main/java/me/adixe/votereward/api/HttpTransport.java @@ -0,0 +1,14 @@ +package me.adixe.votereward.api; + +import java.io.IOException; +import java.net.URI; +import java.time.Duration; +import java.util.Map; + +/** + * Performs HTTP GET requests. Kept behind an interface so the API client can be + * tested without a network and the HTTP library can be swapped. + */ +public interface HttpTransport { + HttpResult get(URI uri, Map headers, Duration timeout) throws IOException, InterruptedException; +} diff --git a/src/main/java/me/adixe/votereward/api/JdkHttpTransport.java b/src/main/java/me/adixe/votereward/api/JdkHttpTransport.java new file mode 100644 index 0000000..3fedaf7 --- /dev/null +++ b/src/main/java/me/adixe/votereward/api/JdkHttpTransport.java @@ -0,0 +1,37 @@ +package me.adixe.votereward.api; + +import java.io.IOException; +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.time.Duration; +import java.util.Map; + +/** + * {@link HttpTransport} on the JDK's own {@link HttpClient} (Java 11+), so the plugin + * needs no HTTP library on any server version. + */ +public final class JdkHttpTransport implements HttpTransport { + private final HttpClient client; + + public JdkHttpTransport() { + this.client = HttpClient.newBuilder() + .connectTimeout(Duration.ofSeconds(10)) + .followRedirects(HttpClient.Redirect.NORMAL) + .build(); + } + + @Override + public HttpResult get(URI uri, Map headers, Duration timeout) + throws IOException, InterruptedException { + HttpRequest.Builder request = HttpRequest.newBuilder(uri).GET().timeout(timeout); + headers.forEach(request::header); + + HttpResponse response = client.send(request.build(), + HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8)); + + return new HttpResult(response.statusCode(), response.body()); + } +} diff --git a/src/main/java/me/adixe/votereward/api/ListApiVoteSource.java b/src/main/java/me/adixe/votereward/api/ListApiVoteSource.java new file mode 100644 index 0000000..38aca60 --- /dev/null +++ b/src/main/java/me/adixe/votereward/api/ListApiVoteSource.java @@ -0,0 +1,133 @@ +package me.adixe.votereward.api; + +import me.adixe.votereward.site.VoteSite; +import me.adixe.votereward.vote.Vote; + +import java.io.IOException; +import java.net.URI; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +/** + * {@link VoteSource} backed by the vote lists' REST API: + * {@code GET {address}/api/v1/servers/{uuid}/votes}. + * + *

Only new votes are requested — {@code createdAt[after]} narrows the query to the time + * since the last check and {@code order[createdAt]=asc} returns them oldest first — so a + * check costs the list one small query instead of the server's whole vote history. + * Pages are followed through {@code view.next}, at most {@link #MAX_PAGES} per call; a larger + * backlog is picked up by the next call, which starts from the newest vote returned here. + */ +public final class ListApiVoteSource implements VoteSource { + public static final String VOTES_PATH = "/api/v1/servers/%s/votes"; + + /** Pages read per check; the API serves 30 votes a page, so 600 votes per list per check. */ + public static final int MAX_PAGES = 20; + + public static final Duration TIMEOUT = Duration.ofSeconds(10); + + private final HttpTransport transport; + private final VotePageParser parser; + private final String userAgent; + + public ListApiVoteSource(HttpTransport transport, VotePageParser parser, String userAgent) { + this.transport = transport; + this.parser = parser; + this.userAgent = userAgent; + } + + @Override + public List votesSince(VoteSite site, Instant since) throws VoteSourceException { + List votes = new ArrayList<>(); + URI uri = firstPage(site, since); + + for (int page = 0; page < MAX_PAGES && uri != null; page++) { + VotePage result = fetch(site, uri); + votes.addAll(result.votes()); + uri = result.next().map(next -> resolveNext(site, next)).orElse(null); + } + + return votes; + } + + URI firstPage(VoteSite site, Instant since) { + Map query = new LinkedHashMap<>(); + // Inclusive: votes in the same second as the last one seen are re-read and de-duplicated by ID. + query.put("createdAt[after]", since.truncatedTo(ChronoUnit.SECONDS).toString()); + query.put("order[createdAt]", "asc"); + + return site.address().resolve(String.format(VOTES_PATH, site.serverId()) + "?" + encode(query)); + } + + private VotePage fetch(VoteSite site, URI uri) throws VoteSourceException { + HttpResult response; + + try { + response = transport.get(uri, headers(), TIMEOUT); + } catch (IOException exception) { + throw new VoteSourceException("Could not reach " + site.address() + ": " + describe(exception), exception); + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new VoteSourceException("Interrupted while querying " + site.address() + ".", exception); + } + + if (response.status() == 429) { + throw new VoteSourceException(site.address() + " is rate limiting requests (HTTP 429)" + + " — increase polling.interval."); + } + + if (!response.isSuccessful()) { + throw new VoteSourceException(site.address() + " answered HTTP " + response.status() + "."); + } + + return parser.parse(response.body()); + } + + /** Follows only links on the same list, never to another host. */ + private static URI resolveNext(VoteSite site, String next) { + URI base = site.address().uri(); + URI resolved = base.resolve(next); + + if (!base.getHost().equalsIgnoreCase(resolved.getHost())) { + return null; + } + + return resolved; + } + + private Map headers() { + Map headers = new LinkedHashMap<>(); + headers.put("Accept", "application/ld+json"); + headers.put("User-Agent", userAgent); + + return headers; + } + + private static String encode(Map query) { + StringBuilder builder = new StringBuilder(); + + for (Map.Entry entry : query.entrySet()) { + if (builder.length() > 0) { + builder.append('&'); + } + + builder.append(URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8)) + .append('=') + .append(URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8)); + } + + return builder.toString(); + } + + private static String describe(IOException exception) { + return Optional.ofNullable(exception.getMessage()).orElse(exception.getClass().getSimpleName()); + } +} diff --git a/src/main/java/me/adixe/votereward/api/VotePage.java b/src/main/java/me/adixe/votereward/api/VotePage.java new file mode 100644 index 0000000..a3b0fa1 --- /dev/null +++ b/src/main/java/me/adixe/votereward/api/VotePage.java @@ -0,0 +1,17 @@ +package me.adixe.votereward.api; + +import me.adixe.votereward.vote.Vote; + +import java.util.List; +import java.util.Optional; + +/** + * One page of the votes collection. + * + * @param next link to the following page as given by the API, usually a path with a query + */ +public record VotePage(List votes, Optional next) { + public VotePage { + votes = List.copyOf(votes); + } +} diff --git a/src/main/java/me/adixe/votereward/api/VotePageParser.java b/src/main/java/me/adixe/votereward/api/VotePageParser.java new file mode 100644 index 0000000..2b00e97 --- /dev/null +++ b/src/main/java/me/adixe/votereward/api/VotePageParser.java @@ -0,0 +1,122 @@ +package me.adixe.votereward.api; + +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.JsonParser; +import me.adixe.votereward.vote.Vote; + +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.time.format.DateTimeParseException; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +/** + * Reads a page of {@code GET /api/v1/servers/{uuid}/votes}. + * + *

Accepts the JSON-LD (Hydra) collection — {@code member} and {@code view.next}, or their + * {@code hydra:}-prefixed names used by older API Platform versions — as well as a plain + * JSON array. An entry without an ID or a readable date is skipped rather than failing the page. + */ +public final class VotePageParser { + public VotePage parse(String body) throws VoteSourceException { + JsonElement root; + + try { + root = JsonParser.parseString(body); + } catch (JsonParseException exception) { + throw new VoteSourceException("The vote list returned invalid JSON.", exception); + } + + if (root.isJsonArray()) { + return new VotePage(votes(root.getAsJsonArray()), Optional.empty()); + } + + if (!root.isJsonObject()) { + throw new VoteSourceException("The vote list returned an unexpected response."); + } + + JsonObject object = root.getAsJsonObject(); + JsonElement members = first(object, "member", "hydra:member"); + + if (members == null || !members.isJsonArray()) { + throw new VoteSourceException("The vote list response has no \"member\" list."); + } + + return new VotePage(votes(members.getAsJsonArray()), next(object)); + } + + private static List votes(JsonArray entries) { + List votes = new ArrayList<>(entries.size()); + + for (JsonElement entry : entries) { + if (!entry.isJsonObject()) { + continue; + } + + JsonObject object = entry.getAsJsonObject(); + String id = string(object, "uuid"); + Instant castAt = instant(string(object, "createdAt")); + + if (id == null || id.isBlank() || castAt == null) { + continue; + } + + votes.add(Vote.of(id, string(object, "nickname"), castAt)); + } + + return votes; + } + + private static Optional next(JsonObject collection) { + JsonElement view = first(collection, "view", "hydra:view"); + + if (view == null || !view.isJsonObject()) { + return Optional.empty(); + } + + return Optional.ofNullable(first(view.getAsJsonObject(), "next", "hydra:next")) + .filter(JsonElement::isJsonPrimitive) + .map(JsonElement::getAsString) + .filter(next -> !next.isBlank()); + } + + private static Instant instant(String value) { + if (value == null) { + return null; + } + + try { + return OffsetDateTime.parse(value).toInstant(); + } catch (DateTimeParseException ignored) { + // The lists store UTC; a date without an offset is read as UTC. + } + + try { + return LocalDateTime.parse(value).toInstant(ZoneOffset.UTC); + } catch (DateTimeParseException ignored) { + return null; + } + } + + private static String string(JsonObject object, String key) { + JsonElement element = object.get(key); + + return element == null || !element.isJsonPrimitive() ? null : element.getAsString(); + } + + private static JsonElement first(JsonObject object, String... keys) { + for (String key : keys) { + if (object.has(key)) { + return object.get(key); + } + } + + return null; + } +} diff --git a/src/main/java/me/adixe/votereward/api/VoteSource.java b/src/main/java/me/adixe/votereward/api/VoteSource.java new file mode 100644 index 0000000..3f8654b --- /dev/null +++ b/src/main/java/me/adixe/votereward/api/VoteSource.java @@ -0,0 +1,19 @@ +package me.adixe.votereward.api; + +import me.adixe.votereward.site.VoteSite; +import me.adixe.votereward.vote.Vote; + +import java.time.Instant; +import java.util.List; + +/** + * Where votes come from. + */ +public interface VoteSource { + /** + * Votes cast for the site's server at or after {@code since}, oldest first. + * May return only the oldest part of a large backlog; the caller continues from the + * last returned vote on its next call. + */ + List votesSince(VoteSite site, Instant since) throws VoteSourceException; +} diff --git a/src/main/java/me/adixe/votereward/api/VoteSourceException.java b/src/main/java/me/adixe/votereward/api/VoteSourceException.java new file mode 100644 index 0000000..1861fe0 --- /dev/null +++ b/src/main/java/me/adixe/votereward/api/VoteSourceException.java @@ -0,0 +1,14 @@ +package me.adixe.votereward.api; + +/** + * The vote list could not be queried or answered with something unreadable. + */ +public class VoteSourceException extends Exception { + public VoteSourceException(String message) { + super(message); + } + + public VoteSourceException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/src/main/java/me/adixe/votereward/bukkit/BukkitConfigView.java b/src/main/java/me/adixe/votereward/bukkit/BukkitConfigView.java new file mode 100644 index 0000000..7affe08 --- /dev/null +++ b/src/main/java/me/adixe/votereward/bukkit/BukkitConfigView.java @@ -0,0 +1,38 @@ +package me.adixe.votereward.bukkit; + +import me.adixe.votereward.config.ConfigView; +import org.bukkit.configuration.ConfigurationSection; + +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Optional; +import java.util.Set; + +/** + * {@link ConfigView} over a Bukkit YAML file. + */ +public final class BukkitConfigView implements ConfigView { + private final ConfigurationSection section; + + public BukkitConfigView(ConfigurationSection section) { + this.section = section; + } + + @Override + public Optional string(String path) { + // getString also turns numbers into text, so "interval: 30" works as well as "30s". + return Optional.ofNullable(section.getString(path)); + } + + @Override + public List stringList(String path) { + return section.getStringList(path); + } + + @Override + public Set childKeys(String path) { + ConfigurationSection child = section.getConfigurationSection(path); + + return child == null ? Set.of() : new LinkedHashSet<>(child.getKeys(false)); + } +} diff --git a/src/main/java/me/adixe/votereward/bukkit/BukkitRewardDispatcher.java b/src/main/java/me/adixe/votereward/bukkit/BukkitRewardDispatcher.java new file mode 100644 index 0000000..e2d4270 --- /dev/null +++ b/src/main/java/me/adixe/votereward/bukkit/BukkitRewardDispatcher.java @@ -0,0 +1,57 @@ +package me.adixe.votereward.bukkit; + +import me.adixe.votereward.ledger.PendingReward; +import me.adixe.votereward.reward.Reward; +import me.adixe.votereward.reward.RewardDispatcher; +import me.adixe.votereward.site.RewardCommand; +import me.adixe.votereward.text.Placeholders; +import me.adixe.votereward.vote.Nickname; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; + +import java.util.List; +import java.util.function.Consumer; + +/** + * Runs the reward commands from the console and thanks the player. + */ +public final class BukkitRewardDispatcher implements RewardDispatcher { + private final TaskScheduler scheduler; + private final Messages messages; + + public BukkitRewardDispatcher(TaskScheduler scheduler, Messages messages) { + this.scheduler = scheduler; + this.messages = messages; + } + + @Override + public void dispatch(Nickname nickname, List rewards, Consumer undelivered) { + // Commands may only be dispatched on the main thread (Folia: the global region). + scheduler.runSync(() -> { + Player player = Bukkit.getPlayerExact(nickname.value()); + + for (Reward reward : rewards) { + if (player == null || !player.isOnline()) { + undelivered.accept(reward.pending()); + continue; + } + + Placeholders placeholders = placeholders(player, reward); + + for (RewardCommand command : reward.site().rewardCommands()) { + Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command.render(placeholders)); + } + + messages.send(player, "reward-received", placeholders); + } + }); + } + + static Placeholders placeholders(Player player, Reward reward) { + return Placeholders.of("player_name", player.getName()) + .with("player_display_name", player.getDisplayName()) + .with("player_uuid", player.getUniqueId()) + .with("server_name", reward.site().name()) + .with("server_address", reward.site().address()); + } +} diff --git a/src/main/java/me/adixe/votereward/bukkit/BukkitTaskScheduler.java b/src/main/java/me/adixe/votereward/bukkit/BukkitTaskScheduler.java new file mode 100644 index 0000000..2b6c63d --- /dev/null +++ b/src/main/java/me/adixe/votereward/bukkit/BukkitTaskScheduler.java @@ -0,0 +1,44 @@ +package me.adixe.votereward.bukkit; + +import org.bukkit.Bukkit; +import org.bukkit.plugin.Plugin; + +import java.time.Duration; + +/** + * {@link TaskScheduler} for CraftBukkit, Spigot, Paper, Purpur and their forks. + */ +final class BukkitTaskScheduler implements TaskScheduler { + private static final long MILLIS_PER_TICK = 50; + + private final Plugin plugin; + + BukkitTaskScheduler(Plugin plugin) { + this.plugin = plugin; + } + + @Override + public void runAsync(Runnable task) { + Bukkit.getScheduler().runTaskAsynchronously(plugin, task); + } + + @Override + public void runAsyncRepeating(Runnable task, Duration period) { + long ticks = Math.max(1, period.toMillis() / MILLIS_PER_TICK); + Bukkit.getScheduler().runTaskTimerAsynchronously(plugin, task, ticks, ticks); + } + + @Override + public void runSync(Runnable task) { + if (Bukkit.isPrimaryThread()) { + task.run(); + } else { + Bukkit.getScheduler().runTask(plugin, task); + } + } + + @Override + public void cancelAll() { + Bukkit.getScheduler().cancelTasks(plugin); + } +} diff --git a/src/main/java/me/adixe/votereward/bukkit/FoliaTaskScheduler.java b/src/main/java/me/adixe/votereward/bukkit/FoliaTaskScheduler.java new file mode 100644 index 0000000..94ace90 --- /dev/null +++ b/src/main/java/me/adixe/votereward/bukkit/FoliaTaskScheduler.java @@ -0,0 +1,88 @@ +package me.adixe.votereward.bukkit; + +import org.bukkit.Bukkit; +import org.bukkit.plugin.Plugin; + +import java.lang.reflect.Method; +import java.time.Duration; +import java.util.concurrent.TimeUnit; +import java.util.function.Consumer; + +/** + * {@link TaskScheduler} for Folia. Its scheduler API is not part of the Spigot API the + * plugin is compiled against, so it is reached through reflection. + */ +final class FoliaTaskScheduler implements TaskScheduler { + private static final String REGIONIZED_SERVER = "io.papermc.paper.threadedregions.RegionizedServer"; + private static final String ASYNC_SCHEDULER = "io.papermc.paper.threadedregions.scheduler.AsyncScheduler"; + private static final String GLOBAL_SCHEDULER = "io.papermc.paper.threadedregions.scheduler.GlobalRegionScheduler"; + + private final Plugin plugin; + private final Object asyncScheduler; + private final Object globalScheduler; + private final Method runNow; + private final Method runAtFixedRate; + private final Method cancelTasks; + private final Method execute; + + FoliaTaskScheduler(Plugin plugin) { + this.plugin = plugin; + + try { + Class asyncType = Class.forName(ASYNC_SCHEDULER); + Class globalType = Class.forName(GLOBAL_SCHEDULER); + + this.asyncScheduler = Bukkit.getServer().getClass().getMethod("getAsyncScheduler").invoke(Bukkit.getServer()); + this.globalScheduler = Bukkit.getServer().getClass().getMethod("getGlobalRegionScheduler") + .invoke(Bukkit.getServer()); + this.runNow = asyncType.getMethod("runNow", Plugin.class, Consumer.class); + this.runAtFixedRate = asyncType.getMethod("runAtFixedRate", Plugin.class, Consumer.class, + long.class, long.class, TimeUnit.class); + this.cancelTasks = asyncType.getMethod("cancelTasks", Plugin.class); + this.execute = globalType.getMethod("execute", Plugin.class, Runnable.class); + } catch (ReflectiveOperationException exception) { + throw new IllegalStateException("Folia detected, but its scheduler API could not be found.", exception); + } + } + + static boolean isFolia() { + try { + Class.forName(REGIONIZED_SERVER); + + return true; + } catch (ClassNotFoundException exception) { + return false; + } + } + + @Override + public void runAsync(Runnable task) { + invoke(runNow, asyncScheduler, plugin, (Consumer) scheduled -> task.run()); + } + + @Override + public void runAsyncRepeating(Runnable task, Duration period) { + long millis = Math.max(1, period.toMillis()); + invoke(runAtFixedRate, asyncScheduler, plugin, (Consumer) scheduled -> task.run(), + millis, millis, TimeUnit.MILLISECONDS); + } + + @Override + public void runSync(Runnable task) { + invoke(execute, globalScheduler, plugin, task); + } + + @Override + public void cancelAll() { + invoke(cancelTasks, asyncScheduler, plugin); + // Global-region tasks are one-shot here and finish on their own. + } + + private static void invoke(Method method, Object target, Object... arguments) { + try { + method.invoke(target, arguments); + } catch (ReflectiveOperationException exception) { + throw new IllegalStateException("Folia scheduler call " + method.getName() + " failed.", exception); + } + } +} diff --git a/src/main/java/me/adixe/votereward/bukkit/Messages.java b/src/main/java/me/adixe/votereward/bukkit/Messages.java new file mode 100644 index 0000000..18e17e1 --- /dev/null +++ b/src/main/java/me/adixe/votereward/bukkit/Messages.java @@ -0,0 +1,42 @@ +package me.adixe.votereward.bukkit; + +import me.adixe.votereward.text.Placeholders; +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; +import org.bukkit.configuration.file.YamlConfiguration; + +/** + * Texts from {@code messages.yml}, coloured with {@code &} codes. Keys missing from the + * server's file fall back to the defaults shipped in the jar, so an old file keeps working + * after an update that adds messages. + */ +public final class Messages { + private final YamlConfiguration file; + + public Messages(YamlConfiguration file) { + this.file = file; + } + + public String get(String key, Placeholders placeholders) { + String text = file.getString(key); + + if (text == null) { + text = key; + } + + return ChatColor.translateAlternateColorCodes('&', placeholders.apply(text)); + } + + public void send(CommandSender receiver, String key) { + send(receiver, key, Placeholders.empty()); + } + + public void send(CommandSender receiver, String key, Placeholders placeholders) { + String text = get(key, placeholders); + + // An empty message in messages.yml switches it off. + if (!text.isEmpty()) { + receiver.sendMessage(text); + } + } +} diff --git a/src/main/java/me/adixe/votereward/bukkit/PlayerJoinListener.java b/src/main/java/me/adixe/votereward/bukkit/PlayerJoinListener.java new file mode 100644 index 0000000..bf1e7a6 --- /dev/null +++ b/src/main/java/me/adixe/votereward/bukkit/PlayerJoinListener.java @@ -0,0 +1,24 @@ +package me.adixe.votereward.bukkit; + +import me.adixe.votereward.VoteReward; +import me.adixe.votereward.vote.Nickname; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerJoinEvent; + +/** + * Gives a joining player the rewards for votes cast while they were offline. + */ +public final class PlayerJoinListener implements Listener { + private final VoteReward plugin; + + public PlayerJoinListener(VoteReward plugin) { + this.plugin = plugin; + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onJoin(PlayerJoinEvent event) { + plugin.deliver(Nickname.of(event.getPlayer().getName())); + } +} diff --git a/src/main/java/me/adixe/votereward/bukkit/TaskScheduler.java b/src/main/java/me/adixe/votereward/bukkit/TaskScheduler.java new file mode 100644 index 0000000..ad11ed4 --- /dev/null +++ b/src/main/java/me/adixe/votereward/bukkit/TaskScheduler.java @@ -0,0 +1,24 @@ +package me.adixe.votereward.bukkit; + +import java.time.Duration; + +/** + * Runs plugin tasks. Folia has no main thread and rejects the classic Bukkit scheduler, + * so the plugin goes through this interface and picks the implementation at startup. + */ +public interface TaskScheduler { + /** Off the main thread — for HTTP calls and file writes. */ + void runAsync(Runnable task); + + /** Off the main thread, every {@code period}, the first time after {@code period}. */ + void runAsyncRepeating(Runnable task, Duration period); + + /** On the thread allowed to run console commands: the main thread, or Folia's global region. */ + void runSync(Runnable task); + + void cancelAll(); + + static TaskScheduler detect(org.bukkit.plugin.Plugin plugin) { + return FoliaTaskScheduler.isFolia() ? new FoliaTaskScheduler(plugin) : new BukkitTaskScheduler(plugin); + } +} diff --git a/src/main/java/me/adixe/votereward/bukkit/VoteRewardCommand.java b/src/main/java/me/adixe/votereward/bukkit/VoteRewardCommand.java new file mode 100644 index 0000000..93fa924 --- /dev/null +++ b/src/main/java/me/adixe/votereward/bukkit/VoteRewardCommand.java @@ -0,0 +1,154 @@ +package me.adixe.votereward.bukkit; + +import me.adixe.votereward.VoteReward; +import me.adixe.votereward.config.Durations; +import me.adixe.votereward.ledger.PendingReward; +import me.adixe.votereward.site.VoteSite; +import me.adixe.votereward.text.Placeholders; +import me.adixe.votereward.vote.Nickname; +import me.adixe.votereward.vote.VoteDay; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.command.TabExecutor; +import org.bukkit.entity.Player; + +import java.time.Instant; +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; + +/** + * {@code /votereward [reward | check [player] | reload | poll]}, alias {@code /vr}. + */ +public final class VoteRewardCommand implements TabExecutor { + private static final List SUBCOMMANDS = List.of("reward", "check", "reload", "poll"); + + private final VoteReward plugin; + + public VoteRewardCommand(VoteReward plugin) { + this.plugin = plugin; + } + + @Override + public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { + String subcommand = args.length == 0 ? "reward" : args[0].toLowerCase(Locale.ROOT); + + if (!SUBCOMMANDS.contains(subcommand)) { + plugin.messages().send(sender, "command.usage"); + + return true; + } + + if (!sender.hasPermission("votereward." + subcommand)) { + plugin.messages().send(sender, "command.no-permission"); + + return true; + } + + switch (subcommand) { + case "reward" -> reward(sender); + case "check" -> check(sender, args); + case "reload" -> reload(sender); + default -> poll(sender); + } + + return true; + } + + private void reward(CommandSender sender) { + if (!(sender instanceof Player player)) { + plugin.messages().send(sender, "command.only-player"); + + return; + } + + if (plugin.deliver(Nickname.of(player.getName())) == 0) { + plugin.messages().send(sender, "command.reward.none", intervalPlaceholder()); + } + } + + private void check(CommandSender sender, String[] args) { + Nickname nickname; + + if (args.length > 1) { + if (!sender.hasPermission("votereward.check.others")) { + plugin.messages().send(sender, "command.no-permission"); + + return; + } + + nickname = Nickname.of(args[1]); + } else if (sender instanceof Player player) { + nickname = Nickname.of(player.getName()); + } else { + plugin.messages().send(sender, "command.check.no-player"); + + return; + } + + LocalDate today = VoteDay.of(Instant.now()); + List pending = plugin.ledger().pendingFor(nickname); + Placeholders player = Placeholders.of("player_name", nickname.value()); + + plugin.messages().send(sender, "command.check.header", player); + + for (VoteSite site : plugin.settings().sites().all()) { + Placeholders placeholders = player + .with("server_name", site.name()) + .with("server_address", site.address()); + + if (pending.stream().anyMatch(reward -> reward.site().equals(site.name()))) { + plugin.messages().send(sender, "command.check.pending", placeholders); + } else if (plugin.ledger().wasRewarded(site.name(), nickname, today)) { + plugin.messages().send(sender, "command.check.rewarded", placeholders); + } else { + plugin.messages().send(sender, "command.check.not-voted", placeholders); + } + } + } + + private void reload(CommandSender sender) { + if (plugin.reload()) { + plugin.messages().send(sender, "command.reload.done", intervalPlaceholder()); + } else { + plugin.messages().send(sender, "command.reload.failed"); + } + } + + private void poll(CommandSender sender) { + plugin.messages().send(sender, "command.poll.started"); + plugin.pollNow(report -> plugin.messages().send(sender, "command.poll.done", + Placeholders.of("checked", report.sitesChecked()) + .with("failed", report.sitesFailed()) + .with("votes", report.votesRead()) + .with("rewards", report.rewardsEarned()))); + } + + private Placeholders intervalPlaceholder() { + return Placeholders.of("interval", Durations.format(plugin.settings().pollInterval())); + } + + @Override + public List onTabComplete(CommandSender sender, Command command, String alias, String[] args) { + List matches = new ArrayList<>(); + + if (args.length == 1) { + for (String subcommand : SUBCOMMANDS) { + if (subcommand.startsWith(args[0].toLowerCase(Locale.ROOT)) + && sender.hasPermission("votereward." + subcommand)) { + matches.add(subcommand); + } + } + } else if (args.length == 2 && args[0].equalsIgnoreCase("check") + && sender.hasPermission("votereward.check.others")) { + for (Player player : sender.getServer().getOnlinePlayers()) { + if (player.getName().toLowerCase(Locale.ROOT).startsWith(args[1].toLowerCase(Locale.ROOT))) { + matches.add(player.getName()); + } + } + } + + return matches; + } +} diff --git a/src/main/java/me/adixe/votereward/commands/CheckCommand.java b/src/main/java/me/adixe/votereward/commands/CheckCommand.java deleted file mode 100644 index 14a6d58..0000000 --- a/src/main/java/me/adixe/votereward/commands/CheckCommand.java +++ /dev/null @@ -1,73 +0,0 @@ -package me.adixe.votereward.commands; - -import me.adixe.commonutilslib.command.CommandException; -import me.adixe.commonutilslib.command.CommandExecutor; -import me.adixe.commonutilslib.command.arg.PlayerArg; -import me.adixe.commonutilslib.configuration.Configuration; -import me.adixe.commonutilslib.configuration.SectionHolder; -import me.adixe.commonutilslib.placeholder.PlaceholderManager; -import me.adixe.votereward.VoteReward; -import me.adixe.votereward.vote.ServerHolder; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import org.simpleyaml.configuration.ConfigurationSection; -import org.simpleyaml.configuration.file.YamlFile; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class CheckCommand extends CommandExecutor { - public CheckCommand(String name, String permission, SectionHolder messagesHolder) { - super(name, permission, messagesHolder, - List.of(new PlayerArg("player")), 0); - } - - @Override - protected void execute(CommandSender sender, Map argsValues) throws CommandException { - VoteReward plugin = VoteReward.getInstance(); - - YamlFile settings = plugin.getConfiguration().get("settings"); - - PlaceholderManager placeholderManager = plugin.getPlaceholderManager(); - - if (argsValues.containsKey("player")) { - Player player = (Player) argsValues.get("player"); - - Map placeholders = new HashMap<>( - placeholderManager.get(Player.class).getUnique(player)); - - sendMessage(sender, "header.other", placeholders); - - for (ConfigurationSection serverSettings : Configuration.getSections(settings, "servers")) { - ServerHolder server = new ServerHolder(serverSettings); - - Map serverPlaceholders = new HashMap<>(placeholders); - serverPlaceholders.putAll(placeholderManager.get(ServerHolder.class).getUnique(server)); - - if (plugin.getVoteManager().isRewardGranted(player, server)) { - sendMessage(sender, "success.other", serverPlaceholders); - } else { - sendMessage(sender, "not-granted.other", serverPlaceholders); - } - } - } else if (sender instanceof Player player) { - sendMessage(sender, "header.self"); - - for (ConfigurationSection serverSettings : Configuration.getSections(settings, "servers")) { - ServerHolder server = new ServerHolder(serverSettings); - - Map serverPlaceholders = new HashMap<>( - placeholderManager.get(ServerHolder.class).getUnique(server)); - - if (plugin.getVoteManager().isRewardGranted(player, server)) { - sendMessage(sender, "success.self", serverPlaceholders); - } else { - sendMessage(sender, "not-granted.self", serverPlaceholders); - } - } - } else { - throw new CommandException("no-player-given"); - } - } -} diff --git a/src/main/java/me/adixe/votereward/commands/ReloadCommand.java b/src/main/java/me/adixe/votereward/commands/ReloadCommand.java deleted file mode 100644 index 892aefb..0000000 --- a/src/main/java/me/adixe/votereward/commands/ReloadCommand.java +++ /dev/null @@ -1,32 +0,0 @@ -package me.adixe.votereward.commands; - -import me.adixe.commonutilslib.command.CommandExecutor; -import me.adixe.commonutilslib.configuration.SectionHolder; -import me.adixe.votereward.VoteReward; -import org.bukkit.command.CommandSender; - -import java.io.IOException; -import java.util.List; -import java.util.Map; -import java.util.logging.Level; - -public class ReloadCommand extends CommandExecutor { - public ReloadCommand(String name, String permission, SectionHolder messagesHolder) { - super(name, permission, messagesHolder, List.of(), 0); - } - - @Override - protected void execute(CommandSender sender, Map argsValues) { - VoteReward plugin = VoteReward.getInstance(); - - try { - plugin.getConfiguration().reload(); - } catch (IOException exception) { - plugin.getLogger().log(Level.SEVERE, - "An error occurred while loading configuration.", - exception); - } - - sendMessage(sender, "success"); - } -} diff --git a/src/main/java/me/adixe/votereward/commands/RewardCommand.java b/src/main/java/me/adixe/votereward/commands/RewardCommand.java deleted file mode 100644 index c9487e5..0000000 --- a/src/main/java/me/adixe/votereward/commands/RewardCommand.java +++ /dev/null @@ -1,82 +0,0 @@ -package me.adixe.votereward.commands; - -import me.adixe.commonutilslib.command.CommandException; -import me.adixe.commonutilslib.command.CommandExecutor; -import me.adixe.commonutilslib.configuration.Configuration; -import me.adixe.commonutilslib.configuration.SectionHolder; -import me.adixe.commonutilslib.placeholder.PlaceholderManager; -import me.adixe.votereward.VoteReward; -import me.adixe.votereward.vote.ServerHolder; -import me.adixe.votereward.vote.VerificationListener; -import me.adixe.votereward.vote.VoteManager; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import org.simpleyaml.configuration.ConfigurationSection; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.logging.Level; - -public class RewardCommand extends CommandExecutor { - public RewardCommand(String name, String permission, SectionHolder messagesHolder) { - super(name, permission, messagesHolder, List.of(), 0); - } - - @Override - protected void execute(CommandSender sender, Map argsValues) throws CommandException { - if (!(sender instanceof Player player)) { - throw new CommandException("only-player"); - } - - VoteReward plugin = VoteReward.getInstance(); - - PlaceholderManager placeholderManager = plugin.getPlaceholderManager(); - - Map placeholders = new HashMap<>( - placeholderManager.get(Player.class).getUnique(player)); - - sendMessage(sender, "process-started", placeholders); - - for (ConfigurationSection serverSettings : Configuration.getSections( - plugin.getConfiguration().get("settings"), "servers")) { - VoteManager voteManager = plugin.getVoteManager(); - - ServerHolder server = new ServerHolder(serverSettings); - - Map serverPlaceholders = new HashMap<>(placeholders); - serverPlaceholders.putAll(placeholderManager.get(ServerHolder.class).getUnique(server)); - - voteManager.verifyAsync(player, server, new VerificationListener() { - @Override - public void success() { - voteManager.rewardPlayer(player, server); - - sendMessage(sender, "success", serverPlaceholders); - } - - @Override - public void notFound() { - sendMessage(sender, "not-found", serverPlaceholders); - } - - @Override - public void rewardGranted() { - sendMessage(sender, "already-awarded", serverPlaceholders); - } - - @Override - public void exceptionCaught(Exception exception) { - Map exceptionPlaceholders = new HashMap<>(serverPlaceholders); - exceptionPlaceholders.put("exception", exception.getMessage()); - - sendMessage(sender, "exception-caught", exceptionPlaceholders); - - plugin.getLogger().log(Level.SEVERE, - "An error occurred while awarding reward.", - exception); - } - }); - } - } -} diff --git a/src/main/java/me/adixe/votereward/config/ConfigView.java b/src/main/java/me/adixe/votereward/config/ConfigView.java new file mode 100644 index 0000000..2092e25 --- /dev/null +++ b/src/main/java/me/adixe/votereward/config/ConfigView.java @@ -0,0 +1,18 @@ +package me.adixe.votereward.config; + +import java.util.List; +import java.util.Optional; +import java.util.Set; + +/** + * Read-only view of a configuration file, so settings can be parsed and tested + * without the server's YAML classes. Paths use dots: {@code polling.interval}. + */ +public interface ConfigView { + Optional string(String path); + + List stringList(String path); + + /** Direct child keys of the section at {@code path}, in file order; empty when there is no such section. */ + Set childKeys(String path); +} diff --git a/src/main/java/me/adixe/votereward/config/Durations.java b/src/main/java/me/adixe/votereward/config/Durations.java new file mode 100644 index 0000000..afc9dcb --- /dev/null +++ b/src/main/java/me/adixe/votereward/config/Durations.java @@ -0,0 +1,90 @@ +package me.adixe.votereward.config; + +import java.time.Duration; +import java.util.Locale; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Parses human-friendly durations from the configuration: {@code 30s}, {@code 5m}, {@code 1h}, + * {@code 7d}, combinations such as {@code 1h30m}, or a bare number of seconds ({@code 30}). + */ +public final class Durations { + private static final Pattern PART = Pattern.compile("(\\d+)\\s*(ms|s|m|h|d)"); + + private Durations() { + } + + public static Duration parse(String raw) { + if (raw == null || raw.isBlank()) { + throw new IllegalArgumentException("Duration is empty."); + } + + String value = raw.trim().toLowerCase(Locale.ROOT); + + if (value.chars().allMatch(Character::isDigit)) { + return Duration.ofSeconds(Long.parseLong(value)); + } + + Matcher matcher = PART.matcher(value); + Duration total = Duration.ZERO; + int consumed = 0; + + while (matcher.find()) { + if (!value.substring(consumed, matcher.start()).isBlank()) { + break; + } + + long amount = Long.parseLong(matcher.group(1)); + + total = total.plus(switch (matcher.group(2)) { + case "ms" -> Duration.ofMillis(amount); + case "s" -> Duration.ofSeconds(amount); + case "m" -> Duration.ofMinutes(amount); + case "h" -> Duration.ofHours(amount); + default -> Duration.ofDays(amount); + }); + consumed = matcher.end(); + } + + if (consumed == 0 || !value.substring(consumed).isBlank()) { + throw new IllegalArgumentException( + "Invalid duration \"" + raw + "\" — use e.g. 30s, 5m, 1h, 7d."); + } + + return total; + } + + /** The shortest readable form, e.g. {@code 90s} → {@code 1m30s}. */ + public static String format(Duration duration) { + long seconds = duration.getSeconds(); + + if (seconds == 0) { + return duration.toMillis() + "ms"; + } + + StringBuilder builder = new StringBuilder(); + long days = seconds / 86_400; + long hours = seconds % 86_400 / 3_600; + long minutes = seconds % 3_600 / 60; + long rest = seconds % 60; + + if (days > 0) { + builder.append(days).append('d'); + } + + if (hours > 0) { + builder.append(hours).append('h'); + } + + if (minutes > 0) { + builder.append(minutes).append('m'); + } + + if (rest > 0) { + builder.append(rest).append('s'); + } + + return builder.toString(); + } +} diff --git a/src/main/java/me/adixe/votereward/config/Settings.java b/src/main/java/me/adixe/votereward/config/Settings.java new file mode 100644 index 0000000..b8abb10 --- /dev/null +++ b/src/main/java/me/adixe/votereward/config/Settings.java @@ -0,0 +1,29 @@ +package me.adixe.votereward.config; + +import me.adixe.votereward.site.VoteSites; + +import java.time.Duration; +import java.util.Objects; + +/** + * Everything read from {@code settings.yml}. + * + * @param pollInterval how often every list is checked for new votes + * @param sites the configured vote lists + */ +public record Settings(Duration pollInterval, VoteSites sites) { + public static final Duration DEFAULT_POLL_INTERVAL = Duration.ofSeconds(30); + + /** The lists rate-limit their API; checking more often gains nothing and risks a block. */ + public static final Duration MIN_POLL_INTERVAL = Duration.ofSeconds(10); + + public Settings { + Objects.requireNonNull(pollInterval, "pollInterval"); + Objects.requireNonNull(sites, "sites"); + + if (pollInterval.compareTo(MIN_POLL_INTERVAL) < 0) { + throw new IllegalArgumentException("polling.interval must be at least " + + Durations.format(MIN_POLL_INTERVAL) + "."); + } + } +} diff --git a/src/main/java/me/adixe/votereward/config/SettingsParser.java b/src/main/java/me/adixe/votereward/config/SettingsParser.java new file mode 100644 index 0000000..1fa36ee --- /dev/null +++ b/src/main/java/me/adixe/votereward/config/SettingsParser.java @@ -0,0 +1,100 @@ +package me.adixe.votereward.config; + +import me.adixe.votereward.site.ListAddress; +import me.adixe.votereward.site.RewardCommand; +import me.adixe.votereward.site.VoteSite; +import me.adixe.votereward.site.VoteSites; +import me.adixe.votereward.vote.ServerId; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +/** + * Builds {@link Settings} from {@code settings.yml}. A wrong value never stops the plugin: + * it falls back to the default (or the list entry is skipped) and a warning says why, + * so one typo does not switch off rewards for every list. + */ +public final class SettingsParser { + public Result parse(ConfigView config) { + List warnings = new ArrayList<>(); + + return new Result(new Settings(pollInterval(config, warnings), sites(config, warnings)), + List.copyOf(warnings)); + } + + private static Duration pollInterval(ConfigView config, List warnings) { + Optional raw = config.string("polling.interval").filter(value -> !value.isBlank()); + + if (raw.isEmpty()) { + return Settings.DEFAULT_POLL_INTERVAL; + } + + Duration interval; + + try { + interval = Durations.parse(raw.get()); + } catch (IllegalArgumentException exception) { + warnings.add("polling.interval: " + exception.getMessage() + " Using " + + Durations.format(Settings.DEFAULT_POLL_INTERVAL) + "."); + + return Settings.DEFAULT_POLL_INTERVAL; + } + + if (interval.compareTo(Settings.MIN_POLL_INTERVAL) < 0) { + warnings.add("polling.interval is below the minimum of " + Durations.format(Settings.MIN_POLL_INTERVAL) + + " — using " + Durations.format(Settings.MIN_POLL_INTERVAL) + "."); + + return Settings.MIN_POLL_INTERVAL; + } + + return interval; + } + + private static VoteSites sites(ConfigView config, List warnings) { + List sites = new ArrayList<>(); + + for (String name : config.childKeys("servers")) { + String path = "servers." + name; + + try { + ListAddress address = ListAddress.of(required(config, path + ".address")); + ServerId serverId = ServerId.of(required(config, path + ".uuid")); + List commands = new ArrayList<>(); + + for (String command : config.stringList(path + ".reward-commands")) { + if (!command.isBlank()) { + commands.add(new RewardCommand(command)); + } + } + + if (commands.isEmpty()) { + warnings.add(path + " has no reward-commands — votes there will give nothing."); + } + + sites.add(new VoteSite(name, address, serverId, commands)); + } catch (IllegalArgumentException exception) { + warnings.add(path + " skipped: " + exception.getMessage()); + } + } + + if (sites.isEmpty()) { + warnings.add("No valid entries under \"servers\" — no votes will be checked."); + } + + return new VoteSites(sites); + } + + private static String required(ConfigView config, String path) { + return config.string(path) + .filter(value -> !value.isBlank()) + .orElseThrow(() -> new IllegalArgumentException("missing \"" + path + "\".")); + } + + /** + * @param warnings problems found in the file, for the server log + */ + public record Result(Settings settings, List warnings) { + } +} diff --git a/src/main/java/me/adixe/votereward/ledger/LedgerRepository.java b/src/main/java/me/adixe/votereward/ledger/LedgerRepository.java new file mode 100644 index 0000000..66582a3 --- /dev/null +++ b/src/main/java/me/adixe/votereward/ledger/LedgerRepository.java @@ -0,0 +1,12 @@ +package me.adixe.votereward.ledger; + +import java.io.IOException; + +/** + * Persists the {@link VoteLedger} between restarts. + */ +public interface LedgerRepository { + LedgerSnapshot load() throws IOException; + + void save(LedgerSnapshot snapshot) throws IOException; +} diff --git a/src/main/java/me/adixe/votereward/ledger/LedgerSnapshot.java b/src/main/java/me/adixe/votereward/ledger/LedgerSnapshot.java new file mode 100644 index 0000000..4d5ed8f --- /dev/null +++ b/src/main/java/me/adixe/votereward/ledger/LedgerSnapshot.java @@ -0,0 +1,24 @@ +package me.adixe.votereward.ledger; + +import java.time.LocalDate; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * Plain copy of the {@link VoteLedger} state for saving and loading. + * + * @param cursors read position per list name + * @param rewarded per vote day and list name: nickname keys already rewarded that day + * @param pending rewards waiting for their player + */ +public record LedgerSnapshot(Map cursors, Map>> rewarded, + List pending) { + public static final LedgerSnapshot EMPTY = new LedgerSnapshot(Map.of(), Map.of(), List.of()); + + public LedgerSnapshot { + cursors = Map.copyOf(cursors); + rewarded = Map.copyOf(rewarded); + pending = List.copyOf(pending); + } +} diff --git a/src/main/java/me/adixe/votereward/ledger/PendingReward.java b/src/main/java/me/adixe/votereward/ledger/PendingReward.java new file mode 100644 index 0000000..2dbb50f --- /dev/null +++ b/src/main/java/me/adixe/votereward/ledger/PendingReward.java @@ -0,0 +1,23 @@ +package me.adixe.votereward.ledger; + +import me.adixe.votereward.vote.Nickname; + +import java.time.Instant; +import java.util.Objects; + +/** + * A reward earned by a vote but not yet given to the player. + * + * @param voteId the vote that earned it + * @param site name of the configured list the vote was cast on + * @param nickname who voted + * @param castAt when the vote was cast + */ +public record PendingReward(String voteId, String site, Nickname nickname, Instant castAt) { + public PendingReward { + Objects.requireNonNull(voteId, "voteId"); + Objects.requireNonNull(site, "site"); + Objects.requireNonNull(nickname, "nickname"); + Objects.requireNonNull(castAt, "castAt"); + } +} diff --git a/src/main/java/me/adixe/votereward/ledger/SiteCursor.java b/src/main/java/me/adixe/votereward/ledger/SiteCursor.java new file mode 100644 index 0000000..875b31e --- /dev/null +++ b/src/main/java/me/adixe/votereward/ledger/SiteCursor.java @@ -0,0 +1,19 @@ +package me.adixe.votereward.ledger; + +import java.time.Instant; +import java.util.Map; +import java.util.Objects; + +/** + * How far one list has been read. + * + * @param position the next check asks for votes from this moment on + * @param recentVotes IDs (with cast time) of votes already handled at or after {@code position}, + * which the next check will see again and must skip + */ +public record SiteCursor(Instant position, Map recentVotes) { + public SiteCursor { + Objects.requireNonNull(position, "position"); + recentVotes = Map.copyOf(recentVotes); + } +} diff --git a/src/main/java/me/adixe/votereward/ledger/VoteLedger.java b/src/main/java/me/adixe/votereward/ledger/VoteLedger.java new file mode 100644 index 0000000..4e5a0a7 --- /dev/null +++ b/src/main/java/me/adixe/votereward/ledger/VoteLedger.java @@ -0,0 +1,253 @@ +package me.adixe.votereward.ledger; + +import me.adixe.votereward.vote.Nickname; +import me.adixe.votereward.vote.Vote; +import me.adixe.votereward.vote.VoteDay; + +import java.time.Duration; +import java.time.Instant; +import java.time.LocalDate; +import java.time.temporal.ChronoUnit; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; + +/** + * The plugin's memory of votes: how far each list has been read, who was rewarded on which + * day, and which rewards still wait for their player. + * + *

Rules it guarantees: + *

    + *
  • every vote is turned into a reward at most once, even when a check sees it again;
  • + *
  • a nickname is rewarded at most once per list per vote day (UTC), like the lists + * themselves allow one vote a day;
  • + *
  • a reward is handed out at most once — it leaves the ledger before it is given.
  • + *
+ * Thread-safe: checks run off the main thread while players join and claim on it. + */ +public final class VoteLedger { + /** + * Every check overlaps the previous one by this much, so a vote that shows up late with + * an older timestamp (clock drift between the list and this server, a slow database + * commit) is still found. Votes read twice are recognised by their ID. + */ + public static final Duration SAFETY_MARGIN = Duration.ofMinutes(5); + + /** How far back the very first check of a list looks. */ + public static final Duration INITIAL_LOOKBACK = Duration.ofHours(1); + + /** The furthest back a check reaches, e.g. after the server was offline for a while. */ + public static final Duration MAX_CATCH_UP = Duration.ofHours(24); + + /** Rewards nobody collected for this long are dropped. */ + public static final Duration PENDING_EXPIRY = Duration.ofDays(7); + + /** Days of "already rewarded" history kept: today and yesterday cover the UTC day boundary. */ + private static final int REWARDED_DAYS_KEPT = 2; + + private final Map cursors; + private final Map>> rewarded; + private final List pending; + private boolean dirty; + + private VoteLedger(LedgerSnapshot snapshot) { + this.cursors = new HashMap<>(snapshot.cursors()); + this.rewarded = new HashMap<>(); + snapshot.rewarded().forEach((day, sites) -> { + Map> copy = new HashMap<>(); + sites.forEach((site, nicknames) -> copy.put(site, new HashSet<>(nicknames))); + rewarded.put(day, copy); + }); + this.pending = new ArrayList<>(snapshot.pending()); + } + + public static VoteLedger empty() { + return new VoteLedger(LedgerSnapshot.EMPTY); + } + + public static VoteLedger restore(LedgerSnapshot snapshot) { + return new VoteLedger(snapshot); + } + + /** + * Where the next check of {@code site} starts: where the previous one left off, or + * {@link #INITIAL_LOOKBACK} ago for a list never checked — but never further back + * than {@link #MAX_CATCH_UP}. + */ + public synchronized Instant checkFrom(String site, Instant now) { + Instant oldestAllowed = now.minus(MAX_CATCH_UP); + Instant from = Optional.ofNullable(cursors.get(site)) + .map(SiteCursor::position) + .orElse(now.minus(INITIAL_LOOKBACK)); + + return from.isBefore(oldestAllowed) ? oldestAllowed : from; + } + + /** + * Records the result of a check and returns the rewards it earned. + * + * @param votes votes returned by the list, in any order + * @param checkedAt when the check was made + */ + public synchronized List record(String site, List votes, Instant checkedAt) { + SiteCursor cursor = cursors.get(site); + Map seen = new HashMap<>(cursor == null ? Map.of() : cursor.recentVotes()); + List earned = new ArrayList<>(); + Instant latest = null; + + List ordered = new ArrayList<>(votes); + ordered.sort(Comparator.comparing(Vote::castAt)); + + for (Vote vote : ordered) { + if (latest == null || vote.castAt().isAfter(latest)) { + latest = vote.castAt(); + } + + if (seen.putIfAbsent(vote.id(), vote.castAt()) != null) { + continue; + } + + if (vote.nickname().isEmpty()) { + continue; + } + + Nickname nickname = vote.nickname().get(); + Set rewardedThatDay = rewarded + .computeIfAbsent(VoteDay.of(vote.castAt()), day -> new HashMap<>()) + .computeIfAbsent(site, name -> new HashSet<>()); + + if (!rewardedThatDay.add(nickname.key())) { + continue; + } + + PendingReward reward = new PendingReward(vote.id(), site, nickname, vote.castAt()); + pending.add(reward); + earned.add(reward); + } + + // Start the next check SAFETY_MARGIN before this one — or at the newest vote returned, + // if that is older: the source may have returned only the oldest part of a backlog. + Instant position = checkedAt.minus(SAFETY_MARGIN); + + if (latest != null && latest.isBefore(position)) { + position = latest; + } + + // The next query includes the cursor's own second, so only votes from that second on can come back. + Instant keepFrom = position.truncatedTo(ChronoUnit.SECONDS); + seen.values().removeIf(castAt -> castAt.isBefore(keepFrom)); + + cursors.put(site, new SiteCursor(position, seen)); + pruneRewardedDays(VoteDay.of(checkedAt)); + dirty = true; + + return earned; + } + + /** Removes and returns every reward waiting for {@code nickname}, oldest first. */ + public synchronized List takePending(Nickname nickname) { + List taken = new ArrayList<>(); + Iterator iterator = pending.iterator(); + + while (iterator.hasNext()) { + PendingReward reward = iterator.next(); + + if (reward.nickname().equals(nickname)) { + taken.add(reward); + iterator.remove(); + } + } + + if (!taken.isEmpty()) { + dirty = true; + } + + return taken; + } + + /** Puts back a reward that could not be given after all, e.g. the player left meanwhile. */ + public synchronized void returnPending(PendingReward reward) { + if (!pending.contains(reward)) { + pending.add(reward); + pending.sort(Comparator.comparing(PendingReward::castAt)); + dirty = true; + } + } + + public synchronized List pendingFor(Nickname nickname) { + List result = new ArrayList<>(); + + for (PendingReward reward : pending) { + if (reward.nickname().equals(nickname)) { + result.add(reward); + } + } + + return result; + } + + /** Whether {@code nickname} earned a reward on {@code site} for a vote cast on {@code day}. */ + public synchronized boolean wasRewarded(String site, Nickname nickname, LocalDate day) { + return rewarded.getOrDefault(day, Map.of()).getOrDefault(site, Set.of()).contains(nickname.key()); + } + + /** Drops rewards nobody collected within {@link #PENDING_EXPIRY}; returns them for logging. */ + public synchronized List expirePending(Instant now) { + Instant oldestKept = now.minus(PENDING_EXPIRY); + List expired = new ArrayList<>(); + Iterator iterator = pending.iterator(); + + while (iterator.hasNext()) { + PendingReward reward = iterator.next(); + + if (reward.castAt().isBefore(oldestKept)) { + expired.add(reward); + iterator.remove(); + } + } + + if (!expired.isEmpty()) { + dirty = true; + } + + return expired; + } + + /** Forgets lists that are no longer configured, so their state does not pile up. */ + public synchronized void retainSites(Set sites) { + if (cursors.keySet().retainAll(sites)) { + dirty = true; + } + } + + public synchronized LedgerSnapshot snapshot() { + Map>> rewardedCopy = new HashMap<>(); + rewarded.forEach((day, sites) -> { + Map> copy = new HashMap<>(); + sites.forEach((site, nicknames) -> copy.put(site, Set.copyOf(nicknames))); + rewardedCopy.put(day, copy); + }); + + return new LedgerSnapshot(cursors, rewardedCopy, pending); + } + + /** Whether anything changed since the last {@link #markSaved()}. */ + public synchronized boolean isDirty() { + return dirty; + } + + public synchronized void markSaved() { + dirty = false; + } + + private void pruneRewardedDays(LocalDate today) { + LocalDate oldestKept = today.minusDays(REWARDED_DAYS_KEPT - 1L); + rewarded.keySet().removeIf(day -> day.isBefore(oldestKept)); + } +} diff --git a/src/main/java/me/adixe/votereward/ledger/YamlLedgerRepository.java b/src/main/java/me/adixe/votereward/ledger/YamlLedgerRepository.java new file mode 100644 index 0000000..3357d09 --- /dev/null +++ b/src/main/java/me/adixe/votereward/ledger/YamlLedgerRepository.java @@ -0,0 +1,197 @@ +package me.adixe.votereward.ledger; + +import me.adixe.votereward.vote.Nickname; +import org.yaml.snakeyaml.DumperOptions; +import org.yaml.snakeyaml.Yaml; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.AtomicMoveNotSupportedException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.time.Instant; +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; +import java.util.TreeSet; + +/** + * Keeps the ledger in a YAML file ({@code plugins/VoteReward/data/ledger.yml}). + * Uses SnakeYAML, which every Bukkit-based server ships. + * + *
+ * cursors:
+ *   lista-minecraft:
+ *     position: '2026-10-25T09:00:00Z'
+ *     recent-votes: {3f2c…: '2026-10-25T09:04:12Z'}
+ * rewarded:
+ *   '2026-10-25': {lista-minecraft: [steve]}
+ * pending:
+ *   - {vote: 3f2c…, site: lista-minecraft, nickname: Steve, cast-at: '2026-10-25T09:04:12Z'}
+ * 
+ */ +public final class YamlLedgerRepository implements LedgerRepository { + private final Path file; + + public YamlLedgerRepository(Path file) { + this.file = file; + } + + @Override + public synchronized LedgerSnapshot load() throws IOException { + if (!Files.exists(file)) { + return LedgerSnapshot.EMPTY; + } + + Object root = new Yaml().load(Files.readString(file, StandardCharsets.UTF_8)); + + if (!(root instanceof Map data)) { + return LedgerSnapshot.EMPTY; + } + + try { + return new LedgerSnapshot(cursors(data.get("cursors")), rewarded(data.get("rewarded")), + pending(data.get("pending"))); + } catch (RuntimeException exception) { + throw new IOException("Vote data in " + file + " is damaged: " + exception.getMessage(), exception); + } + } + + @Override + public synchronized void save(LedgerSnapshot snapshot) throws IOException { + Map data = new LinkedHashMap<>(); + data.put("cursors", encodeCursors(snapshot.cursors())); + data.put("rewarded", encodeRewarded(snapshot.rewarded())); + data.put("pending", encodePending(snapshot.pending())); + + DumperOptions options = new DumperOptions(); + options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); + + Files.createDirectories(file.toAbsolutePath().getParent()); + Path temporary = file.resolveSibling(file.getFileName() + ".tmp"); + Files.writeString(temporary, new Yaml(options).dump(data), StandardCharsets.UTF_8); + + // Write-then-move, so a crash mid-write never leaves a half-written file behind. + try { + Files.move(temporary, file, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); + } catch (AtomicMoveNotSupportedException exception) { + Files.move(temporary, file, StandardCopyOption.REPLACE_EXISTING); + } + } + + private static Map encodeCursors(Map cursors) { + Map encoded = new TreeMap<>(); + + cursors.forEach((site, cursor) -> { + Map recent = new TreeMap<>(); + cursor.recentVotes().forEach((id, castAt) -> recent.put(id, castAt.toString())); + + Map entry = new LinkedHashMap<>(); + entry.put("position", cursor.position().toString()); + entry.put("recent-votes", recent); + encoded.put(site, entry); + }); + + return encoded; + } + + private static Map encodeRewarded(Map>> rewarded) { + Map encoded = new TreeMap<>(); + + rewarded.forEach((day, sites) -> { + Map perSite = new TreeMap<>(); + sites.forEach((site, nicknames) -> perSite.put(site, new ArrayList<>(new TreeSet<>(nicknames)))); + encoded.put(day.toString(), perSite); + }); + + return encoded; + } + + private static List encodePending(List pending) { + List encoded = new ArrayList<>(); + + for (PendingReward reward : pending) { + Map entry = new LinkedHashMap<>(); + entry.put("vote", reward.voteId()); + entry.put("site", reward.site()); + entry.put("nickname", reward.nickname().value()); + entry.put("cast-at", reward.castAt().toString()); + encoded.add(entry); + } + + return encoded; + } + + private static Map cursors(Object raw) { + Map cursors = new HashMap<>(); + + map(raw).forEach((site, value) -> { + Map entry = map(value); + Map recent = new HashMap<>(); + map(entry.get("recent-votes")).forEach((id, castAt) -> recent.put(id, instant(castAt))); + cursors.put(site, new SiteCursor(instant(entry.get("position")), recent)); + }); + + return cursors; + } + + private static Map>> rewarded(Object raw) { + Map>> rewarded = new HashMap<>(); + + map(raw).forEach((day, value) -> { + Map> perSite = new HashMap<>(); + map(value).forEach((site, nicknames) -> perSite.put(site, strings(nicknames))); + rewarded.put(LocalDate.parse(day), perSite); + }); + + return rewarded; + } + + private static List pending(Object raw) { + List pending = new ArrayList<>(); + + if (raw instanceof Collection entries) { + for (Object value : entries) { + Map entry = map(value); + pending.add(new PendingReward(String.valueOf(entry.get("vote")), String.valueOf(entry.get("site")), + Nickname.of(String.valueOf(entry.get("nickname"))), instant(entry.get("cast-at")))); + } + } + + return pending; + } + + private static Map map(Object raw) { + Map result = new LinkedHashMap<>(); + + if (raw instanceof Map map) { + map.forEach((key, value) -> result.put(String.valueOf(key), value)); + } + + return result; + } + + private static Set strings(Object raw) { + Set result = new HashSet<>(); + + if (raw instanceof Collection values) { + values.forEach(value -> result.add(String.valueOf(value))); + } + + return result; + } + + private static Instant instant(Object raw) { + // A hand-edited file may hold an unquoted timestamp, which SnakeYAML reads as a Date. + return raw instanceof Date date ? date.toInstant() : Instant.parse(String.valueOf(raw)); + } +} diff --git a/src/main/java/me/adixe/votereward/placeholder/ServerHolderProvider.java b/src/main/java/me/adixe/votereward/placeholder/ServerHolderProvider.java deleted file mode 100644 index ddcb78a..0000000 --- a/src/main/java/me/adixe/votereward/placeholder/ServerHolderProvider.java +++ /dev/null @@ -1,22 +0,0 @@ -package me.adixe.votereward.placeholder; - -import me.adixe.commonutilslib.placeholder.Provider; -import me.adixe.votereward.vote.ServerHolder; - -import java.util.HashMap; -import java.util.Map; - -public class ServerHolderProvider extends Provider { - public ServerHolderProvider(String defaultPrefix) { - super(ServerHolder.class, defaultPrefix); - } - - @Override - public Map get(ServerHolder server) { - Map placeholders = new HashMap<>(); - placeholders.put("name", server.name()); - placeholders.put("address", server.address()); - - return placeholders; - } -} diff --git a/src/main/java/me/adixe/votereward/reward/PlayerDirectory.java b/src/main/java/me/adixe/votereward/reward/PlayerDirectory.java new file mode 100644 index 0000000..610cc60 --- /dev/null +++ b/src/main/java/me/adixe/votereward/reward/PlayerDirectory.java @@ -0,0 +1,10 @@ +package me.adixe.votereward.reward; + +import me.adixe.votereward.vote.Nickname; + +/** + * Who is on the server right now. + */ +public interface PlayerDirectory { + boolean isOnline(Nickname nickname); +} diff --git a/src/main/java/me/adixe/votereward/reward/PollReport.java b/src/main/java/me/adixe/votereward/reward/PollReport.java new file mode 100644 index 0000000..d48ac76 --- /dev/null +++ b/src/main/java/me/adixe/votereward/reward/PollReport.java @@ -0,0 +1,10 @@ +package me.adixe.votereward.reward; + +/** + * Outcome of one check of every list. + * + * @param skipped true when the check did not run because the previous one was still going + */ +public record PollReport(int sitesChecked, int sitesFailed, int votesRead, int rewardsEarned, boolean skipped) { + public static final PollReport SKIPPED = new PollReport(0, 0, 0, 0, true); +} diff --git a/src/main/java/me/adixe/votereward/reward/Reward.java b/src/main/java/me/adixe/votereward/reward/Reward.java new file mode 100644 index 0000000..00472b3 --- /dev/null +++ b/src/main/java/me/adixe/votereward/reward/Reward.java @@ -0,0 +1,16 @@ +package me.adixe.votereward.reward; + +import me.adixe.votereward.ledger.PendingReward; +import me.adixe.votereward.site.VoteSite; + +import java.util.Objects; + +/** + * A pending reward together with the list entry whose commands it runs. + */ +public record Reward(PendingReward pending, VoteSite site) { + public Reward { + Objects.requireNonNull(pending, "pending"); + Objects.requireNonNull(site, "site"); + } +} diff --git a/src/main/java/me/adixe/votereward/reward/RewardDispatcher.java b/src/main/java/me/adixe/votereward/reward/RewardDispatcher.java new file mode 100644 index 0000000..4277fa1 --- /dev/null +++ b/src/main/java/me/adixe/votereward/reward/RewardDispatcher.java @@ -0,0 +1,19 @@ +package me.adixe.votereward.reward; + +import me.adixe.votereward.ledger.PendingReward; +import me.adixe.votereward.vote.Nickname; + +import java.util.List; +import java.util.function.Consumer; + +/** + * Gives rewards on the server: runs the reward commands and tells the player. + * Implementations decide on which thread that happens. + */ +public interface RewardDispatcher { + /** + * @param undelivered called for every reward that could not be given (the player left + * in the meantime), so it can wait for the next join + */ + void dispatch(Nickname player, List rewards, Consumer undelivered); +} diff --git a/src/main/java/me/adixe/votereward/reward/RewardService.java b/src/main/java/me/adixe/votereward/reward/RewardService.java new file mode 100644 index 0000000..2b83734 --- /dev/null +++ b/src/main/java/me/adixe/votereward/reward/RewardService.java @@ -0,0 +1,75 @@ +package me.adixe.votereward.reward; + +import me.adixe.votereward.ledger.PendingReward; +import me.adixe.votereward.ledger.VoteLedger; +import me.adixe.votereward.site.VoteSite; +import me.adixe.votereward.site.VoteSites; +import me.adixe.votereward.vote.Nickname; + +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.logging.Logger; + +/** + * Hands earned rewards to players: right away when they are online, otherwise when they join. + */ +public final class RewardService { + private final VoteLedger ledger; + private final VoteSites sites; + private final PlayerDirectory players; + private final RewardDispatcher dispatcher; + private final Logger logger; + + public RewardService(VoteLedger ledger, VoteSites sites, PlayerDirectory players, RewardDispatcher dispatcher, + Logger logger) { + this.ledger = ledger; + this.sites = sites; + this.players = players; + this.dispatcher = dispatcher; + this.logger = logger; + } + + /** + * Gives the player every reward waiting for them. + * + * @return how many rewards were handed to the dispatcher + */ + public int deliver(Nickname player) { + List rewards = new ArrayList<>(); + + for (PendingReward pending : ledger.takePending(player)) { + Optional site = sites.find(pending.site()); + + if (site.isPresent()) { + rewards.add(new Reward(pending, site.get())); + } else { + logger.warning("Dropped " + player + "'s reward for a vote on \"" + pending.site() + + "\": that list is no longer in settings.yml."); + } + } + + if (!rewards.isEmpty()) { + dispatcher.dispatch(player, rewards, ledger::returnPending); + } + + return rewards.size(); + } + + /** A check found new rewards: give them to the players who are online now. */ + public void rewardsEarned(List earned) { + Set voters = new LinkedHashSet<>(); + + for (PendingReward reward : earned) { + voters.add(reward.nickname()); + } + + for (Nickname voter : voters) { + if (players.isOnline(voter)) { + deliver(voter); + } + } + } +} diff --git a/src/main/java/me/adixe/votereward/reward/VotePoller.java b/src/main/java/me/adixe/votereward/reward/VotePoller.java new file mode 100644 index 0000000..c42580b --- /dev/null +++ b/src/main/java/me/adixe/votereward/reward/VotePoller.java @@ -0,0 +1,139 @@ +package me.adixe.votereward.reward; + +import me.adixe.votereward.api.VoteSource; +import me.adixe.votereward.api.VoteSourceException; +import me.adixe.votereward.config.Durations; +import me.adixe.votereward.config.Settings; +import me.adixe.votereward.ledger.LedgerRepository; +import me.adixe.votereward.ledger.PendingReward; +import me.adixe.votereward.ledger.VoteLedger; +import me.adixe.votereward.site.VoteSite; +import me.adixe.votereward.vote.Vote; + +import java.io.IOException; +import java.time.Clock; +import java.time.Instant; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * One check of every configured list: fetch new votes, record them in the ledger, save it, + * and hand the earned rewards to the {@link RewardService}. Run every + * {@code polling.interval} off the main thread. + * + *

A list that cannot be reached is logged once when it starts failing and once when it + * recovers, not on every check, so an outage does not flood the console. + */ +public final class VotePoller { + private final Settings settings; + private final VoteSource source; + private final VoteLedger ledger; + private final LedgerRepository repository; + private final RewardService rewards; + private final Clock clock; + private final Logger logger; + + private final AtomicBoolean running = new AtomicBoolean(); + private final Set failingSites = new HashSet<>(); + + public VotePoller(Settings settings, VoteSource source, VoteLedger ledger, LedgerRepository repository, + RewardService rewards, Clock clock, Logger logger) { + this.settings = settings; + this.source = source; + this.ledger = ledger; + this.repository = repository; + this.rewards = rewards; + this.clock = clock; + this.logger = logger; + } + + public PollReport poll() { + if (!running.compareAndSet(false, true)) { + return PollReport.SKIPPED; + } + + try { + return pollAllSites(); + } finally { + running.set(false); + } + } + + private PollReport pollAllSites() { + List earned = new ArrayList<>(); + int checked = 0; + int failed = 0; + int read = 0; + + for (VoteSite site : settings.sites().all()) { + Instant now = clock.instant(); + + try { + List votes = source.votesSince(site, ledger.checkFrom(site.name(), now)); + earned.addAll(ledger.record(site.name(), votes, now)); + read += votes.size(); + checked++; + recovered(site); + } catch (VoteSourceException exception) { + failed++; + failing(site, exception); + } catch (RuntimeException exception) { + failed++; + logger.log(Level.SEVERE, "Unexpected error while checking votes on " + site.name() + ".", exception); + } + } + + for (PendingReward expired : ledger.expirePending(clock.instant())) { + logger.info("Dropped " + expired.nickname() + "'s uncollected reward for a vote on " + + expired.site() + " (not collected within " + + Durations.format(VoteLedger.PENDING_EXPIRY) + ")."); + } + + save(); + + if (!earned.isEmpty()) { + rewards.rewardsEarned(earned); + } + + return new PollReport(checked, failed, read, earned.size(), false); + } + + /** Writes the ledger if it changed. Also called on shutdown. */ + public void save() { + if (!ledger.isDirty()) { + return; + } + + try { + repository.save(ledger.snapshot()); + ledger.markSaved(); + } catch (IOException exception) { + logger.log(Level.SEVERE, "Could not save vote data.", exception); + } + } + + private void failing(VoteSite site, VoteSourceException exception) { + synchronized (failingSites) { + if (failingSites.add(site.name())) { + logger.warning("Could not check votes on " + site.name() + ": " + exception.getMessage() + + " Retrying every " + Durations.format(settings.pollInterval()) + + "; votes cast meanwhile will be picked up."); + } else { + logger.log(Level.FINE, "Still cannot check votes on " + site.name() + ".", exception); + } + } + } + + private void recovered(VoteSite site) { + synchronized (failingSites) { + if (failingSites.remove(site.name())) { + logger.info("Checking votes on " + site.name() + " works again."); + } + } + } +} diff --git a/src/main/java/me/adixe/votereward/site/ListAddress.java b/src/main/java/me/adixe/votereward/site/ListAddress.java new file mode 100644 index 0000000..ecc8a66 --- /dev/null +++ b/src/main/java/me/adixe/votereward/site/ListAddress.java @@ -0,0 +1,85 @@ +package me.adixe.votereward.site; + +import java.net.URI; +import java.net.URISyntaxException; +import java.util.Locale; +import java.util.Objects; + +/** + * Base address of a vote list, e.g. {@code https://lista-minecraft.pl}. Every list + * exposes the same API under it, so this is all that is needed to reach a server's votes. + */ +public final class ListAddress { + private final URI uri; + + private ListAddress(URI uri) { + this.uri = uri; + } + + public static ListAddress of(String raw) { + if (raw == null || raw.isBlank()) { + throw new IllegalArgumentException("List address is empty."); + } + + String trimmed = raw.trim(); + + while (trimmed.endsWith("/")) { + trimmed = trimmed.substring(0, trimmed.length() - 1); + } + + URI uri; + + try { + uri = new URI(trimmed); + } catch (URISyntaxException exception) { + throw new IllegalArgumentException("List address is not a valid URL: " + raw, exception); + } + + String scheme = uri.getScheme() == null ? "" : uri.getScheme().toLowerCase(Locale.ROOT); + + // http is accepted for local development against a mock or a locally running list. + if (!scheme.equals("https") && !scheme.equals("http")) { + throw new IllegalArgumentException("List address must start with https:// — got: " + raw); + } + + if (uri.getHost() == null) { + throw new IllegalArgumentException("List address has no host: " + raw); + } + + if (uri.getQuery() != null || uri.getFragment() != null) { + throw new IllegalArgumentException("List address must not contain ? or #: " + raw); + } + + return new ListAddress(uri); + } + + public URI uri() { + return uri; + } + + public String host() { + return uri.getHost(); + } + + /** Resolves a path such as {@code /api/v1/servers/…/votes} against this list. */ + public URI resolve(String absolutePath) { + String base = uri.toString(); + + return URI.create(base + (absolutePath.startsWith("/") ? absolutePath : "/" + absolutePath)); + } + + @Override + public boolean equals(Object other) { + return other instanceof ListAddress address && uri.equals(address.uri); + } + + @Override + public int hashCode() { + return Objects.hash(uri); + } + + @Override + public String toString() { + return uri.toString(); + } +} diff --git a/src/main/java/me/adixe/votereward/site/RewardCommand.java b/src/main/java/me/adixe/votereward/site/RewardCommand.java new file mode 100644 index 0000000..088ae65 --- /dev/null +++ b/src/main/java/me/adixe/votereward/site/RewardCommand.java @@ -0,0 +1,25 @@ +package me.adixe.votereward.site; + +import me.adixe.votereward.text.Placeholders; + +/** + * A console command run when a player is rewarded, e.g. {@code give %player_name% diamond}. + */ +public record RewardCommand(String template) { + public RewardCommand { + if (template == null || template.isBlank()) { + throw new IllegalArgumentException("Reward command is empty."); + } + + template = template.trim(); + + // Commands are dispatched from the console, which takes them without the slash. + if (template.startsWith("/")) { + template = template.substring(1); + } + } + + public String render(Placeholders placeholders) { + return placeholders.apply(template); + } +} diff --git a/src/main/java/me/adixe/votereward/site/VoteSite.java b/src/main/java/me/adixe/votereward/site/VoteSite.java new file mode 100644 index 0000000..69ba64a --- /dev/null +++ b/src/main/java/me/adixe/votereward/site/VoteSite.java @@ -0,0 +1,26 @@ +package me.adixe.votereward.site; + +import me.adixe.votereward.vote.ServerId; + +import java.util.List; +import java.util.Objects; + +/** + * One configured vote list entry: where the server is listed and what voting there earns. + * + * @param name unique key from the configuration, e.g. {@code lista-minecraft} + * @param address base address of the list + * @param serverId the server's ID on that list + * @param rewardCommands commands run for every rewarded vote + */ +public record VoteSite(String name, ListAddress address, ServerId serverId, List rewardCommands) { + public VoteSite { + if (name == null || name.isBlank()) { + throw new IllegalArgumentException("Site name is empty."); + } + + Objects.requireNonNull(address, "address"); + Objects.requireNonNull(serverId, "serverId"); + rewardCommands = List.copyOf(rewardCommands); + } +} diff --git a/src/main/java/me/adixe/votereward/site/VoteSites.java b/src/main/java/me/adixe/votereward/site/VoteSites.java new file mode 100644 index 0000000..43d35f8 --- /dev/null +++ b/src/main/java/me/adixe/votereward/site/VoteSites.java @@ -0,0 +1,38 @@ +package me.adixe.votereward.site; + +import java.util.Collection; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +/** + * The configured vote lists, in configuration order, looked up by name. + */ +public final class VoteSites { + private final Map byName; + + public VoteSites(Collection sites) { + Map map = new LinkedHashMap<>(); + + for (VoteSite site : sites) { + if (map.putIfAbsent(site.name(), site) != null) { + throw new IllegalArgumentException("Duplicate site name: " + site.name()); + } + } + + this.byName = map; + } + + public Optional find(String name) { + return Optional.ofNullable(byName.get(name)); + } + + public List all() { + return List.copyOf(byName.values()); + } + + public boolean isEmpty() { + return byName.isEmpty(); + } +} diff --git a/src/main/java/me/adixe/votereward/text/Placeholders.java b/src/main/java/me/adixe/votereward/text/Placeholders.java new file mode 100644 index 0000000..63e0b1e --- /dev/null +++ b/src/main/java/me/adixe/votereward/text/Placeholders.java @@ -0,0 +1,54 @@ +package me.adixe.votereward.text; + +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * Immutable set of {@code %name%} placeholders substituted into messages and commands. + */ +public final class Placeholders { + private static final Placeholders EMPTY = new Placeholders(Collections.emptyMap()); + + private final Map values; + + private Placeholders(Map values) { + this.values = values; + } + + public static Placeholders empty() { + return EMPTY; + } + + public static Placeholders of(String key, Object value) { + return EMPTY.with(key, value); + } + + public Placeholders with(String key, Object value) { + Map copy = new LinkedHashMap<>(values); + copy.put(key, String.valueOf(value)); + + return new Placeholders(Collections.unmodifiableMap(copy)); + } + + public Placeholders with(Placeholders other) { + Map copy = new LinkedHashMap<>(values); + copy.putAll(other.values); + + return new Placeholders(Collections.unmodifiableMap(copy)); + } + + public String apply(String text) { + String result = text; + + for (Map.Entry entry : values.entrySet()) { + result = result.replace("%" + entry.getKey() + "%", entry.getValue()); + } + + return result; + } + + public Map asMap() { + return values; + } +} diff --git a/src/main/java/me/adixe/votereward/vote/Nickname.java b/src/main/java/me/adixe/votereward/vote/Nickname.java new file mode 100644 index 0000000..791ef35 --- /dev/null +++ b/src/main/java/me/adixe/votereward/vote/Nickname.java @@ -0,0 +1,51 @@ +package me.adixe.votereward.vote; + +import java.util.Locale; +import java.util.Objects; + +/** + * A player name as typed on the vote list. Minecraft names are case-insensitive, + * so two nicknames are equal when they differ only in letter case. + */ +public final class Nickname { + private final String value; + private final String key; + + private Nickname(String value) { + this.value = value; + this.key = value.toLowerCase(Locale.ROOT); + } + + public static Nickname of(String raw) { + if (raw == null || raw.isBlank()) { + throw new IllegalArgumentException("Nickname is empty."); + } + + return new Nickname(raw.trim()); + } + + /** The nickname as written by the player. */ + public String value() { + return value; + } + + /** Case-insensitive form, used for storage and lookups. */ + public String key() { + return key; + } + + @Override + public boolean equals(Object other) { + return other instanceof Nickname nickname && key.equals(nickname.key); + } + + @Override + public int hashCode() { + return Objects.hash(key); + } + + @Override + public String toString() { + return value; + } +} diff --git a/src/main/java/me/adixe/votereward/vote/ServerHolder.java b/src/main/java/me/adixe/votereward/vote/ServerHolder.java deleted file mode 100644 index ce46db6..0000000 --- a/src/main/java/me/adixe/votereward/vote/ServerHolder.java +++ /dev/null @@ -1,19 +0,0 @@ -package me.adixe.votereward.vote; - -import org.simpleyaml.configuration.ConfigurationSection; - -import java.util.List; - -public record ServerHolder(ConfigurationSection settings) { - public String name() { - return settings.getName(); - } - - public String address() { - return settings.getString("address"); - } - - public List rewardCommands() { - return settings.getStringList("reward-commands"); - } -} diff --git a/src/main/java/me/adixe/votereward/vote/ServerId.java b/src/main/java/me/adixe/votereward/vote/ServerId.java new file mode 100644 index 0000000..10c2fbf --- /dev/null +++ b/src/main/java/me/adixe/votereward/vote/ServerId.java @@ -0,0 +1,31 @@ +package me.adixe.votereward.vote; + +import java.util.Objects; +import java.util.UUID; + +/** + * Identifier of a server on a vote list — the UUID shown in the list's server panel + * and in the last segment of the server's page address. + */ +public record ServerId(UUID value) { + public ServerId { + Objects.requireNonNull(value, "value"); + } + + public static ServerId of(String raw) { + if (raw == null || raw.isBlank()) { + throw new IllegalArgumentException("Server ID is empty."); + } + + try { + return new ServerId(UUID.fromString(raw.trim())); + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException("Server ID is not a valid UUID: " + raw, exception); + } + } + + @Override + public String toString() { + return value.toString(); + } +} diff --git a/src/main/java/me/adixe/votereward/vote/VerificationListener.java b/src/main/java/me/adixe/votereward/vote/VerificationListener.java deleted file mode 100644 index c8316fa..0000000 --- a/src/main/java/me/adixe/votereward/vote/VerificationListener.java +++ /dev/null @@ -1,11 +0,0 @@ -package me.adixe.votereward.vote; - -public interface VerificationListener { - void success(); - - void notFound(); - - void rewardGranted(); - - void exceptionCaught(Exception exception); -} diff --git a/src/main/java/me/adixe/votereward/vote/Vote.java b/src/main/java/me/adixe/votereward/vote/Vote.java new file mode 100644 index 0000000..f6d2a7d --- /dev/null +++ b/src/main/java/me/adixe/votereward/vote/Vote.java @@ -0,0 +1,31 @@ +package me.adixe.votereward.vote; + +import java.time.Instant; +import java.util.Objects; +import java.util.Optional; + +/** + * A single vote returned by the vote list API. + * + * @param id the vote's UUID on the list, unique across all votes + * @param nickname the player name given when voting; votes cast without one cannot be rewarded + * @param castAt when the vote was cast + */ +public record Vote(String id, Optional nickname, Instant castAt) { + public Vote { + if (id == null || id.isBlank()) { + throw new IllegalArgumentException("Vote ID is empty."); + } + + Objects.requireNonNull(nickname, "nickname"); + Objects.requireNonNull(castAt, "castAt"); + } + + public static Vote of(String id, String nickname, Instant castAt) { + Optional parsed = nickname == null || nickname.isBlank() + ? Optional.empty() + : Optional.of(Nickname.of(nickname)); + + return new Vote(id, parsed, castAt); + } +} diff --git a/src/main/java/me/adixe/votereward/vote/VoteDay.java b/src/main/java/me/adixe/votereward/vote/VoteDay.java new file mode 100644 index 0000000..f500b8e --- /dev/null +++ b/src/main/java/me/adixe/votereward/vote/VoteDay.java @@ -0,0 +1,18 @@ +package me.adixe.votereward.vote; + +import java.time.Instant; +import java.time.LocalDate; +import java.time.ZoneOffset; + +/** + * The vote lists allow one vote per player per day and count that day in UTC, + * so the "once a day" reward rule uses the same calendar. + */ +public final class VoteDay { + private VoteDay() { + } + + public static LocalDate of(Instant instant) { + return LocalDate.ofInstant(instant, ZoneOffset.UTC); + } +} diff --git a/src/main/java/me/adixe/votereward/vote/VoteManager.java b/src/main/java/me/adixe/votereward/vote/VoteManager.java deleted file mode 100644 index 3c72d05..0000000 --- a/src/main/java/me/adixe/votereward/vote/VoteManager.java +++ /dev/null @@ -1,127 +0,0 @@ -package me.adixe.votereward.vote; - -import me.adixe.commonutilslib.util.MessageUtil; -import me.adixe.votereward.VoteReward; -import me.adixe.votereward.vote.verifier.VoteVerifier; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; - -import java.time.LocalDate; -import java.time.ZoneId; -import java.time.format.DateTimeFormatter; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class VoteManager { - private final List verifiers; - - public VoteManager() { - this.verifiers = new ArrayList<>(); - - Bukkit.getScheduler().runTaskTimerAsynchronously( - VoteReward.getInstance(), this::update, 0L, 20L * 60 * 10); - } - - public void register(VoteVerifier verifier) { - verifiers.add(verifier); - } - - private void update() { - var votes = VoteReward.getInstance().getConfiguration().get("votes"); - - LocalDate timeNow = LocalDate.now(ZoneId.of("Europe/Paris")); - - if (!votes.contains("date") || !LocalDate.parse(votes.getString("date"), - DateTimeFormatter.ISO_LOCAL_DATE).isEqual(timeNow)) { - votes.set("date", timeNow.format(DateTimeFormatter.ISO_LOCAL_DATE)); - - votes.set("votes", null); - } - } - - public void verify(Player player, ServerHolder server, VerificationListener listener) { - if (isRewardGranted(player, server)) { - listener.rewardGranted(); - - return; - } - - for (VoteVerifier verifier : verifiers) { - if (!verifier.canVerify(server)) { - continue; - } - - try { - if (verifier.verify(player, server)) { - listener.success(); - } else { - listener.notFound(); - } - } catch (Exception exception) { - listener.exceptionCaught(exception); - } - - return; - } - - throw new IllegalArgumentException("Invalid server address: " + server.address()); - } - - public void verifyAsync(Player player, ServerHolder server, VerificationListener listener) { - Bukkit.getScheduler().runTaskAsynchronously(VoteReward.getInstance(), - () -> verify(player, server, listener)); - } - - public void rewardPlayer(Player player, ServerHolder server) { - VoteReward plugin = VoteReward.getInstance(); - - if (!isRewardGranted(player, server)) { - var votes = plugin.getConfiguration().get("votes"); - - var votesSettings = votes.contains("votes") ? - votes.getConfigurationSection("votes") : - votes.createSection("votes"); - - List playerServers = getPlayerServers(player); - - playerServers.add(server.name()); - - votesSettings.set(player.getUniqueId().toString(), playerServers); - } - - Bukkit.getScheduler().runTask(plugin, () -> executeRewardCommands(player, server)); - } - - public boolean isRewardGranted(Player player, ServerHolder server) { - return getPlayerServers(player).contains(server.name()); - } - - private List getPlayerServers(Player player) { - List playerServers = new ArrayList<>(); - - var votesSettings = VoteReward.getInstance().getConfiguration() - .get("votes").getConfigurationSection("votes"); - - String playerUuid = player.getUniqueId().toString(); - - if (votesSettings != null && votesSettings.contains(playerUuid)) { - playerServers.addAll(votesSettings.getStringList(playerUuid)); - } - - return playerServers; - } - - private void executeRewardCommands(Player player, ServerHolder server) { - var placeholderManager = VoteReward.getInstance().getPlaceholderManager(); - - Map placeholders = new HashMap<>(); - placeholders.putAll(placeholderManager.get(Player.class).getUnique(player)); - placeholders.putAll(placeholderManager.get(ServerHolder.class).getUnique(server)); - - for (String command : server.rewardCommands()) { - Bukkit.dispatchCommand(Bukkit.getConsoleSender(), MessageUtil.translate(command, placeholders)); - } - } -} diff --git a/src/main/java/me/adixe/votereward/vote/verifier/LMVerifier.java b/src/main/java/me/adixe/votereward/vote/verifier/LMVerifier.java deleted file mode 100644 index 028385f..0000000 --- a/src/main/java/me/adixe/votereward/vote/verifier/LMVerifier.java +++ /dev/null @@ -1,64 +0,0 @@ -package me.adixe.votereward.vote.verifier; - -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; -import me.adixe.votereward.vote.ServerHolder; -import okhttp3.HttpUrl; -import okhttp3.Request; -import okhttp3.Response; -import org.bukkit.entity.Player; - -import java.io.IOException; -import java.time.LocalDate; -import java.time.ZoneId; -import java.time.format.DateTimeFormatter; -import java.util.List; - -public class LMVerifier extends VoteVerifier { - public LMVerifier() { - super(List.of( - "https://lista-minecraft.pl", - "https://lista-serwerow.emecz.pl", - "https://minecraft-list.info")); - } - - @Override - protected boolean process(Player player, ServerHolder server) throws IOException { - HttpUrl.Builder builder = HttpUrl.parse(server.address()).newBuilder() - .addPathSegments("votes/server") - .addPathSegment(server.settings().getString("uuid")); - - Request request = new Request.Builder() - .url(builder.build()) - .build(); - - try (Response response = getClient().newCall(request).execute()) { - LocalDate timeNow = LocalDate.now(ZoneId.of("Europe/Paris")); - - JsonArray entries = JsonParser.parseReader(response.body().charStream()).getAsJsonArray(); - - for (JsonElement entry : entries) { - JsonObject entryObject = entry.getAsJsonObject(); - - JsonElement nicknameElement = entryObject.get("nickname"); - - if (nicknameElement.isJsonNull()) { - continue; - } - - String nickname = nicknameElement.getAsString(); - LocalDate createdAt = LocalDate.parse( - entryObject.get("createdAt").getAsString(), - DateTimeFormatter.ISO_DATE_TIME); - - if (nickname.equalsIgnoreCase(player.getName()) && createdAt.isEqual(timeNow)) { - return true; - } - } - - return false; - } - } -} diff --git a/src/main/java/me/adixe/votereward/vote/verifier/VoteVerifier.java b/src/main/java/me/adixe/votereward/vote/verifier/VoteVerifier.java deleted file mode 100644 index f1d0231..0000000 --- a/src/main/java/me/adixe/votereward/vote/verifier/VoteVerifier.java +++ /dev/null @@ -1,36 +0,0 @@ -package me.adixe.votereward.vote.verifier; - -import me.adixe.votereward.vote.ServerHolder; -import okhttp3.OkHttpClient; -import org.bukkit.entity.Player; - -import java.io.IOException; -import java.util.List; - -public abstract class VoteVerifier { - private final List addresses; - private final OkHttpClient client; - - public VoteVerifier(List addresses) { - this.addresses = addresses; - this.client = new OkHttpClient(); - } - - public boolean verify(Player player, ServerHolder server) throws IOException { - if (!canVerify(server)) { - throw new IllegalArgumentException("Invalid server address: " + server.address()); - } - - return process(player, server); - } - - protected abstract boolean process(Player player, ServerHolder server) throws IOException; - - public boolean canVerify(ServerHolder server) { - return addresses.contains(server.address()); - } - - public OkHttpClient getClient() { - return client; - } -} diff --git a/src/main/resources/messages.yml b/src/main/resources/messages.yml index 02635c4..8720a61 100644 --- a/src/main/resources/messages.yml +++ b/src/main/resources/messages.yml @@ -9,38 +9,25 @@ # # Source code and documentation: https://github.com/dudekm/VoteReward # -# Spigot: Adixe -# Discord: adixepl -# GitHub: AdixePL -# -commands: - missing-subcommand: No command given. - unknown-command: Command "%trigger%" was not found. - invalid-usage: 'Use the correct syntax: %usage%.' - no-permission: You don't have permission to use this command. - no-arg-end: End of arg "%arg%" was not found. +# Colours: & codes (&a green, &c red, &e yellow, &l bold…). An empty message ('') is not sent. + +reward-received: '&aThanks for voting on &e%server_name%&a! Your reward has been given.' + +command: + usage: '&cUsage: /votereward [reward|check [player]|reload|poll]' + no-permission: '&cYou don''t have permission to use this command.' + only-player: '&cOnly a player can use this command.' reward: - process-started: Verifying votes... - success: '%server_name%: Reward has been awarded.' - not-found: '%server_name%: No vote found.' - already-awarded: '%server_name%: Reward has been awarded - already.' - exception-caught: '%server_name%: An error occurred while - verifying vote: %exception%.' - only-player: This command can be executed by the player. + none: '&cNo rewards are waiting for you. Votes are checked every &e%interval%&c — if you have just voted, try again in a moment.' check: - header: - self: 'Your rewards for voting:' - other: '%player_name%''s rewards for voting:' - success: - self: '%server_name%: Reward has been awarded.' - other: '%server_name%: %player_name%''s - reward has been awarded.' - not-granted: - self: '%server_name%: Reward is not awarded.' - other: '%server_name%: %player_name%''s - reward is not awarded.' - player-not-found: Player "%player%" was not found. - no-player-given: No player given. + no-player: '&cGive a player name: /votereward check ' + header: '&aVotes of &e%player_name% &atoday:' + rewarded: '&a- &e%server_name%&a: reward received.' + pending: '&e- %server_name%: reward waiting — use /votereward.' + not-voted: '&c- &e%server_name%&c: no vote yet.' reload: - success: Configuration reloaded. + done: '&aConfiguration reloaded. Checking votes every &e%interval%&a.' + failed: '&cCould not reload the configuration — see the console. The previous one stays active.' + poll: + started: '&aChecking the vote lists...' + done: '&aChecked &e%checked%&a list(s) (&e%failed%&a failed), read &e%votes%&a vote(s), &e%rewards%&a new reward(s).' diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index 038cbd2..289715d 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -1,21 +1,29 @@ name: VoteReward main: me.adixe.votereward.VoteReward -version: 3.2.0 -api-version: 1.18 +version: '${project.version}' +api-version: '1.18' +folia-supported: true authors: [Adixe] description: Reward players for voting for the server. -libraries: - - com.squareup.okhttp3:okhttp:4.12.0 +website: https://github.com/dudekm/VoteReward commands: votereward: - aliases: - - vr + description: Collect vote rewards and manage the plugin. + usage: /votereward [reward|check [player]|reload|poll] + aliases: [vr] permissions: - votereward.command: - default: true votereward.reward: + description: Collect your own vote rewards. default: true votereward.check: + description: See your own vote status for today. + default: true + votereward.check.others: + description: See another player's vote status. default: op votereward.reload: + description: Reload settings.yml and messages.yml. + default: op + votereward.poll: + description: Check the vote lists right now. default: op diff --git a/src/main/resources/settings.yml b/src/main/resources/settings.yml index 32b80fb..a65b0bb 100644 --- a/src/main/resources/settings.yml +++ b/src/main/resources/settings.yml @@ -9,10 +9,20 @@ # # Source code and documentation: https://github.com/dudekm/VoteReward # -# Spigot: Adixe -# Discord: adixepl -# GitHub: AdixePL -# + +polling: + # How often every list below is checked for new votes: 30s, 1m, 5m… + # Each check asks only for votes since the previous one. Minimum: 10s. + interval: 30s + +# The lists your server is on. The names (lista-minecraft…) are up to you, but must be unique. +# address - the list's website +# uuid - your server's ID on that list (last part of your server's page address) +# reward-commands - console commands run for each vote. Placeholders: +# %player_name%, %player_display_name%, %player_uuid%, +# %server_name%, %server_address% +# A player is rewarded at most once a day (UTC) per list. Players who are offline +# when their vote is found get the reward the next time they join. servers: lista-minecraft: address: https://lista-minecraft.pl diff --git a/src/test/java/me/adixe/votereward/TestData.java b/src/test/java/me/adixe/votereward/TestData.java new file mode 100644 index 0000000..c5ef920 --- /dev/null +++ b/src/test/java/me/adixe/votereward/TestData.java @@ -0,0 +1,45 @@ +package me.adixe.votereward; + +import me.adixe.votereward.site.ListAddress; +import me.adixe.votereward.site.RewardCommand; +import me.adixe.votereward.site.VoteSite; +import me.adixe.votereward.vote.ServerId; + +import java.util.List; + +/** + * Shared fixtures for tests. + */ +public final class TestData { + public static final String SERVER_ID = "183413bc-4588-4265-8f06-346963e5d7df"; + + private TestData() { + } + + public static VoteSite site(String name) { + return site(name, "https://lista-minecraft.pl"); + } + + public static VoteSite site(String name, String address) { + return new VoteSite(name, ListAddress.of(address), ServerId.of(SERVER_ID), + List.of(new RewardCommand("give %player_name% diamond"))); + } + + /** One vote in the shape the API returns it. */ + public static String voteJson(String id, String nickname, String createdAt) { + String nick = nickname == null ? "null" : "\"" + nickname + "\""; + + return "{\"@id\":\"/api/v1/votes/" + id + "\",\"@type\":\"Vote\",\"uuid\":\"" + id + + "\",\"nickname\":" + nick + ",\"createdAt\":\"" + createdAt + "\"}"; + } + + /** A JSON-LD collection page as API Platform 4 serves it. */ + public static String page(String next, String... votes) { + String view = next == null + ? "{\"@id\":\"/api/v1/servers/x/votes\",\"@type\":\"PartialCollectionView\"}" + : "{\"@id\":\"/api/v1/servers/x/votes\",\"@type\":\"PartialCollectionView\",\"next\":\"" + next + "\"}"; + + return "{\"@context\":\"/api/v1/contexts/Vote\",\"@id\":\"/api/v1/servers/x/votes\",\"@type\":\"Collection\"," + + "\"totalItems\":" + votes.length + ",\"member\":[" + String.join(",", votes) + "],\"view\":" + view + "}"; + } +} diff --git a/src/test/java/me/adixe/votereward/api/FakeHttpTransport.java b/src/test/java/me/adixe/votereward/api/FakeHttpTransport.java new file mode 100644 index 0000000..caad010 --- /dev/null +++ b/src/test/java/me/adixe/votereward/api/FakeHttpTransport.java @@ -0,0 +1,49 @@ +package me.adixe.votereward.api; + +import java.io.IOException; +import java.net.URI; +import java.time.Duration; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Deque; +import java.util.List; +import java.util.Map; + +/** + * Answers requests with queued responses and remembers what was asked. + */ +final class FakeHttpTransport implements HttpTransport { + final List requests = new ArrayList<>(); + final List> headers = new ArrayList<>(); + private final Deque responses = new ArrayDeque<>(); + + FakeHttpTransport respond(int status, String body) { + responses.add(new HttpResult(status, body)); + + return this; + } + + FakeHttpTransport fail(IOException exception) { + responses.add(exception); + + return this; + } + + @Override + public HttpResult get(URI uri, Map headers, Duration timeout) throws IOException { + requests.add(uri); + this.headers.add(headers); + + Object response = responses.poll(); + + if (response instanceof IOException exception) { + throw exception; + } + + if (response == null) { + throw new AssertionError("Unexpected request: " + uri); + } + + return (HttpResult) response; + } +} diff --git a/src/test/java/me/adixe/votereward/api/ListApiVoteSourceIntegrationTest.java b/src/test/java/me/adixe/votereward/api/ListApiVoteSourceIntegrationTest.java new file mode 100644 index 0000000..4edaff6 --- /dev/null +++ b/src/test/java/me/adixe/votereward/api/ListApiVoteSourceIntegrationTest.java @@ -0,0 +1,80 @@ +package me.adixe.votereward.api; + +import com.sun.net.httpserver.HttpServer; +import me.adixe.votereward.vote.Vote; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.io.OutputStream; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; + +import static me.adixe.votereward.TestData.SERVER_ID; +import static me.adixe.votereward.TestData.page; +import static me.adixe.votereward.TestData.site; +import static me.adixe.votereward.TestData.voteJson; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +/** + * Real HTTP round trip against a local server imitating the vote list API. + */ +class ListApiVoteSourceIntegrationTest { + private final List queries = new CopyOnWriteArrayList<>(); + private HttpServer server; + private String address; + + @BeforeEach + void startServer() throws IOException { + server = HttpServer.create(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0); + server.createContext("/api/v1/servers/" + SERVER_ID + "/votes", exchange -> { + String query = exchange.getRequestURI().getRawQuery(); + queries.add(query); + + String body = query.endsWith("page=2") + ? page(null, voteJson("u2", "Alex", "2026-10-25T09:00:02+00:00")) + : page("/api/v1/servers/" + SERVER_ID + "/votes?" + query + "&page=2", + voteJson("u1", "Steve", "2026-10-25T09:00:01+00:00")); + + byte[] bytes = body.getBytes(StandardCharsets.UTF_8); + exchange.getResponseHeaders().add("Content-Type", "application/ld+json; charset=utf-8"); + exchange.sendResponseHeaders(200, bytes.length); + + try (OutputStream out = exchange.getResponseBody()) { + out.write(bytes); + } + }); + server.start(); + address = "http://127.0.0.1:" + server.getAddress().getPort(); + } + + @AfterEach + void stopServer() { + server.stop(0); + } + + @Test + void fetchesAllPagesOverHttp() throws VoteSourceException { + ListApiVoteSource source = new ListApiVoteSource(new JdkHttpTransport(), new VotePageParser(), "test"); + + List votes = source.votesSince(site("local", address), Instant.parse("2026-10-25T09:00:00Z")); + + assertEquals(List.of("u1", "u2"), votes.stream().map(Vote::id).toList()); + assertEquals("createdAt%5Bafter%5D=2026-10-25T09%3A00%3A00Z&order%5BcreatedAt%5D=asc", queries.get(0)); + } + + @Test + void unknownPathIsAnError() { + ListApiVoteSource source = new ListApiVoteSource(new JdkHttpTransport(), new VotePageParser(), "test"); + + // The JDK server answers 404 for paths without a handler, like the list does for unknown routes. + assertThrows(VoteSourceException.class, + () -> source.votesSince(site("local", address + "/nothing-here"), Instant.now())); + } +} diff --git a/src/test/java/me/adixe/votereward/api/ListApiVoteSourceTest.java b/src/test/java/me/adixe/votereward/api/ListApiVoteSourceTest.java new file mode 100644 index 0000000..9e06464 --- /dev/null +++ b/src/test/java/me/adixe/votereward/api/ListApiVoteSourceTest.java @@ -0,0 +1,90 @@ +package me.adixe.votereward.api; + +import me.adixe.votereward.vote.Vote; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.time.Instant; +import java.util.List; + +import static me.adixe.votereward.TestData.SERVER_ID; +import static me.adixe.votereward.TestData.page; +import static me.adixe.votereward.TestData.site; +import static me.adixe.votereward.TestData.voteJson; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class ListApiVoteSourceTest { + private static final Instant SINCE = Instant.parse("2026-10-25T09:00:00.123Z"); + + private final FakeHttpTransport transport = new FakeHttpTransport(); + private final ListApiVoteSource source = new ListApiVoteSource(transport, new VotePageParser(), "VoteReward/test"); + + @Test + void asksOnlyForVotesSinceTheGivenMomentOldestFirst() throws VoteSourceException { + transport.respond(200, page(null)); + + source.votesSince(site("a"), SINCE); + + assertEquals("https://lista-minecraft.pl/api/v1/servers/" + SERVER_ID + "/votes" + + "?createdAt%5Bafter%5D=2026-10-25T09%3A00%3A00Z&order%5BcreatedAt%5D=asc", + transport.requests.get(0).toString()); + assertEquals("application/ld+json", transport.headers.get(0).get("Accept")); + assertEquals("VoteReward/test", transport.headers.get(0).get("User-Agent")); + } + + @Test + void followsNextPages() throws VoteSourceException { + transport.respond(200, page("/api/v1/servers/x/votes?page=2", voteJson("u1", "Steve", "2026-10-25T09:00:01Z"))) + .respond(200, page(null, voteJson("u2", "Alex", "2026-10-25T09:00:02Z"))); + + List votes = source.votesSince(site("a"), SINCE); + + assertEquals(List.of("u1", "u2"), votes.stream().map(Vote::id).toList()); + assertEquals("https://lista-minecraft.pl/api/v1/servers/x/votes?page=2", transport.requests.get(1).toString()); + } + + @Test + void stopsAfterMaxPages() throws VoteSourceException { + for (int i = 0; i < ListApiVoteSource.MAX_PAGES; i++) { + transport.respond(200, page("/next?page=" + (i + 2), voteJson("u" + i, "P" + i, "2026-10-25T09:00:01Z"))); + } + + assertEquals(ListApiVoteSource.MAX_PAGES, source.votesSince(site("a"), SINCE).size()); + assertEquals(ListApiVoteSource.MAX_PAGES, transport.requests.size()); + } + + @Test + void neverFollowsLinksToAnotherHost() throws VoteSourceException { + transport.respond(200, page("https://evil.example/steal", voteJson("u1", "Steve", "2026-10-25T09:00:01Z"))); + + assertEquals(1, source.votesSince(site("a"), SINCE).size()); + assertEquals(1, transport.requests.size()); + } + + @Test + void reportsRateLimiting() { + transport.respond(429, ""); + + VoteSourceException exception = assertThrows(VoteSourceException.class, + () -> source.votesSince(site("a"), SINCE)); + assertTrue(exception.getMessage().contains("429")); + } + + @Test + void reportsHttpErrors() { + transport.respond(500, "oops"); + + assertThrows(VoteSourceException.class, () -> source.votesSince(site("a"), SINCE)); + } + + @Test + void reportsNetworkErrors() { + transport.fail(new IOException("Connection refused")); + + VoteSourceException exception = assertThrows(VoteSourceException.class, + () -> source.votesSince(site("a"), SINCE)); + assertTrue(exception.getMessage().contains("Connection refused")); + } +} diff --git a/src/test/java/me/adixe/votereward/api/VotePageParserTest.java b/src/test/java/me/adixe/votereward/api/VotePageParserTest.java new file mode 100644 index 0000000..6ef5ec9 --- /dev/null +++ b/src/test/java/me/adixe/votereward/api/VotePageParserTest.java @@ -0,0 +1,89 @@ +package me.adixe.votereward.api; + +import me.adixe.votereward.vote.Nickname; +import me.adixe.votereward.vote.Vote; +import org.junit.jupiter.api.Test; + +import java.time.Instant; +import java.util.Optional; + +import static me.adixe.votereward.TestData.page; +import static me.adixe.votereward.TestData.voteJson; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class VotePageParserTest { + private final VotePageParser parser = new VotePageParser(); + + @Test + void readsJsonLdCollection() throws VoteSourceException { + VotePage page = parser.parse(page("/api/v1/servers/x/votes?page=2", + voteJson("u1", "Steve", "2026-10-25T09:06:41+00:00"), + voteJson("u2", "Alex", "2026-10-25T09:06:41.768Z"))); + + assertEquals(2, page.votes().size()); + + Vote first = page.votes().get(0); + assertEquals("u1", first.id()); + assertEquals(Optional.of(Nickname.of("Steve")), first.nickname()); + assertEquals(Instant.parse("2026-10-25T09:06:41Z"), first.castAt()); + assertEquals(Instant.parse("2026-10-25T09:06:41.768Z"), page.votes().get(1).castAt()); + assertEquals(Optional.of("/api/v1/servers/x/votes?page=2"), page.next()); + } + + @Test + void lastPageHasNoNext() throws VoteSourceException { + assertTrue(parser.parse(page(null, voteJson("u1", "Steve", "2026-10-25T09:00:00Z"))).next().isEmpty()); + } + + @Test + void readsHydraPrefixedNamesOfOlderApiPlatform() throws VoteSourceException { + VotePage page = parser.parse("{\"hydra:member\":[" + voteJson("u1", "Steve", "2026-10-25T09:00:00Z") + + "],\"hydra:view\":{\"hydra:next\":\"/next\"}}"); + + assertEquals(1, page.votes().size()); + assertEquals(Optional.of("/next"), page.next()); + } + + @Test + void readsPlainJsonArray() throws VoteSourceException { + VotePage page = parser.parse("[" + voteJson("u1", "Steve", "2026-10-25T09:00:00Z") + "]"); + + assertEquals(1, page.votes().size()); + assertTrue(page.next().isEmpty()); + } + + @Test + void keepsVotesWithoutNickname() throws VoteSourceException { + VotePage page = parser.parse(page(null, voteJson("u1", null, "2026-10-25T09:00:00Z"))); + + assertTrue(page.votes().get(0).nickname().isEmpty()); + } + + @Test + void readsDateWithoutOffsetAsUtc() throws VoteSourceException { + VotePage page = parser.parse(page(null, voteJson("u1", "Steve", "2026-10-25T09:00:00"))); + + assertEquals(Instant.parse("2026-10-25T09:00:00Z"), page.votes().get(0).castAt()); + } + + @Test + void skipsEntriesWithoutIdOrDate() throws VoteSourceException { + VotePage page = parser.parse(page(null, + "{\"nickname\":\"NoId\",\"createdAt\":\"2026-10-25T09:00:00Z\"}", + voteJson("u2", "BadDate", "yesterday"), + "42", + voteJson("u3", "Ok", "2026-10-25T09:00:00Z"))); + + assertEquals(1, page.votes().size()); + assertEquals("u3", page.votes().get(0).id()); + } + + @Test + void rejectsGarbage() { + assertThrows(VoteSourceException.class, () -> parser.parse("Bad gateway")); + assertThrows(VoteSourceException.class, () -> parser.parse("{\"title\":\"An error occurred\"}")); + assertThrows(VoteSourceException.class, () -> parser.parse("\"text\"")); + } +} diff --git a/src/test/java/me/adixe/votereward/config/DurationsTest.java b/src/test/java/me/adixe/votereward/config/DurationsTest.java new file mode 100644 index 0000000..1898e2a --- /dev/null +++ b/src/test/java/me/adixe/votereward/config/DurationsTest.java @@ -0,0 +1,41 @@ +package me.adixe.votereward.config; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.ValueSource; + +import java.time.Duration; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class DurationsTest { + @ParameterizedTest + @CsvSource({ + "30, 30", + "30s, 30", + "5m, 300", + "1h, 3600", + "1d, 86400", + "1h30m, 5400", + "'1m 30s', 90", + "2M, 120" + }) + void parses(String raw, long seconds) { + assertEquals(Duration.ofSeconds(seconds), Durations.parse(raw)); + } + + @ParameterizedTest + @ValueSource(strings = {"", "abc", "30x", "s30", "30s abc", "-5s"}) + void rejectsInvalid(String raw) { + assertThrows(IllegalArgumentException.class, () -> Durations.parse(raw)); + } + + @Test + void formatsShortestForm() { + assertEquals("30s", Durations.format(Duration.ofSeconds(30))); + assertEquals("1m30s", Durations.format(Duration.ofSeconds(90))); + assertEquals("1d2h", Durations.format(Duration.ofHours(26))); + } +} diff --git a/src/test/java/me/adixe/votereward/config/MapConfigView.java b/src/test/java/me/adixe/votereward/config/MapConfigView.java new file mode 100644 index 0000000..4a5f365 --- /dev/null +++ b/src/test/java/me/adixe/votereward/config/MapConfigView.java @@ -0,0 +1,65 @@ +package me.adixe.votereward.config; + +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; + +/** + * {@link ConfigView} over nested maps, standing in for a YAML file in tests. + */ +public final class MapConfigView implements ConfigView { + private final Map root; + + public MapConfigView(Map root) { + this.root = root; + } + + @Override + public Optional string(String path) { + Object value = get(path); + + return value == null || value instanceof Map || value instanceof List + ? Optional.empty() + : Optional.of(String.valueOf(value)); + } + + @Override + public List stringList(String path) { + List result = new ArrayList<>(); + + if (get(path) instanceof List list) { + list.forEach(item -> result.add(String.valueOf(item))); + } + + return result; + } + + @Override + public Set childKeys(String path) { + return get(path) instanceof Map map ? new LinkedHashSet<>(castKeys(map)) : Set.of(); + } + + private Object get(String path) { + Object current = root; + + for (String part : path.split("\\.")) { + if (!(current instanceof Map map)) { + return null; + } + + current = map.get(part); + } + + return current; + } + + private static Set castKeys(Map map) { + Set keys = new LinkedHashSet<>(); + map.keySet().forEach(key -> keys.add(String.valueOf(key))); + + return keys; + } +} diff --git a/src/test/java/me/adixe/votereward/config/SettingsParserTest.java b/src/test/java/me/adixe/votereward/config/SettingsParserTest.java new file mode 100644 index 0000000..2c02ecd --- /dev/null +++ b/src/test/java/me/adixe/votereward/config/SettingsParserTest.java @@ -0,0 +1,110 @@ +package me.adixe.votereward.config; + +import me.adixe.votereward.site.VoteSite; +import org.junit.jupiter.api.Test; + +import java.time.Duration; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class SettingsParserTest { + private static final String UUID = "183413bc-4588-4265-8f06-346963e5d7df"; + + private final SettingsParser parser = new SettingsParser(); + + @Test + void readsAFullConfiguration() { + SettingsParser.Result result = parser.parse(config(Map.of("interval", "1m"), + site("lista-minecraft", "https://lista-minecraft.pl", UUID, List.of("give %player_name% diamond")))); + + assertEquals(Duration.ofMinutes(1), result.settings().pollInterval()); + assertEquals(List.of(), result.warnings()); + + VoteSite site = result.settings().sites().find("lista-minecraft").orElseThrow(); + assertEquals("https://lista-minecraft.pl", site.address().toString()); + assertEquals(UUID, site.serverId().toString()); + assertEquals("give %player_name% diamond", site.rewardCommands().get(0).template()); + } + + @Test + void pollIntervalDefaultsTo30SecondsWhenMissing() { + // Configuration files from VoteReward 3.x have no "polling" section. + SettingsParser.Result result = parser.parse(config(null, + site("a", "https://a.pl", UUID, List.of("say hi")))); + + assertEquals(Duration.ofSeconds(30), result.settings().pollInterval()); + assertEquals(List.of(), result.warnings()); + } + + @Test + void pollIntervalBelowMinimumIsRaised() { + SettingsParser.Result result = parser.parse(config(Map.of("interval", "1s"), + site("a", "https://a.pl", UUID, List.of("say hi")))); + + assertEquals(Settings.MIN_POLL_INTERVAL, result.settings().pollInterval()); + assertEquals(1, result.warnings().size()); + } + + @Test + void invalidPollIntervalFallsBackToDefault() { + SettingsParser.Result result = parser.parse(config(Map.of("interval", "often"), + site("a", "https://a.pl", UUID, List.of("say hi")))); + + assertEquals(Settings.DEFAULT_POLL_INTERVAL, result.settings().pollInterval()); + assertTrue(result.warnings().get(0).startsWith("polling.interval")); + } + + @Test + void invalidSiteIsSkippedAndTheOthersStay() { + Map servers = new LinkedHashMap<>(); + servers.putAll(site("broken", "https://a.pl", "not-a-uuid", List.of("say hi"))); + servers.putAll(site("good", "https://b.pl", UUID, List.of("say hi"))); + + SettingsParser.Result result = parser.parse(config(null, servers)); + + assertEquals(1, result.settings().sites().all().size()); + assertTrue(result.settings().sites().find("good").isPresent()); + assertTrue(result.warnings().get(0).startsWith("servers.broken skipped")); + } + + @Test + void warnsAboutMissingRewardCommands() { + SettingsParser.Result result = parser.parse(config(null, site("a", "https://a.pl", UUID, List.of()))); + + assertEquals(1, result.settings().sites().all().size()); + assertTrue(result.warnings().get(0).contains("no reward-commands")); + } + + @Test + void warnsWhenNothingIsConfigured() { + SettingsParser.Result result = parser.parse(new MapConfigView(Map.of())); + + assertTrue(result.settings().sites().isEmpty()); + assertEquals(1, result.warnings().size()); + } + + private static Map site(String name, String address, String uuid, List commands) { + Map site = new LinkedHashMap<>(); + site.put("address", address); + site.put("uuid", uuid); + site.put("reward-commands", commands); + + return Map.of(name, site); + } + + private static MapConfigView config(Map polling, Map servers) { + Map root = new LinkedHashMap<>(); + + if (polling != null) { + root.put("polling", polling); + } + + root.put("servers", servers); + + return new MapConfigView(root); + } +} diff --git a/src/test/java/me/adixe/votereward/ledger/VoteLedgerTest.java b/src/test/java/me/adixe/votereward/ledger/VoteLedgerTest.java new file mode 100644 index 0000000..08ca350 --- /dev/null +++ b/src/test/java/me/adixe/votereward/ledger/VoteLedgerTest.java @@ -0,0 +1,155 @@ +package me.adixe.votereward.ledger; + +import me.adixe.votereward.vote.Nickname; +import me.adixe.votereward.vote.Vote; +import org.junit.jupiter.api.Test; + +import java.time.Duration; +import java.time.Instant; +import java.time.LocalDate; +import java.util.List; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class VoteLedgerTest { + private static final Instant NOW = Instant.parse("2026-10-25T12:00:00Z"); + private static final Nickname STEVE = Nickname.of("Steve"); + + private final VoteLedger ledger = VoteLedger.empty(); + + @Test + void firstCheckLooksBackOneHour() { + assertEquals(NOW.minus(VoteLedger.INITIAL_LOOKBACK), ledger.checkFrom("a", NOW)); + } + + @Test + void nextCheckOverlapsThePreviousOneBySafetyMargin() { + ledger.record("a", List.of(), NOW); + + assertEquals(NOW.minus(VoteLedger.SAFETY_MARGIN), ledger.checkFrom("a", NOW.plusSeconds(30))); + } + + @Test + void checkAfterLongDowntimeReachesBackAtMostMaxCatchUp() { + ledger.record("a", List.of(), NOW); + Instant muchLater = NOW.plus(Duration.ofDays(3)); + + assertEquals(muchLater.minus(VoteLedger.MAX_CATCH_UP), ledger.checkFrom("a", muchLater)); + } + + @Test + void continuesFromTheNewestVoteWhenOnlyPartOfABacklogWasRead() { + Instant old = NOW.minus(Duration.ofHours(3)); + ledger.record("a", List.of(vote("u1", "Steve", old)), NOW); + + assertEquals(old, ledger.checkFrom("a", NOW)); + } + + @Test + void voteEarnsAPendingReward() { + List earned = ledger.record("a", List.of(vote("u1", "Steve", NOW)), NOW); + + assertEquals(1, earned.size()); + assertEquals(earned, ledger.pendingFor(Nickname.of("steve"))); + assertTrue(ledger.wasRewarded("a", STEVE, LocalDate.of(2026, 10, 25))); + } + + @Test + void sameVoteSeenTwiceCountsOnce() { + ledger.record("a", List.of(vote("u1", "Steve", NOW)), NOW); + + assertEquals(List.of(), ledger.record("a", List.of(vote("u1", "Steve", NOW)), NOW.plusSeconds(30))); + assertEquals(1, ledger.pendingFor(STEVE).size()); + } + + @Test + void oneRewardPerNicknamePerListPerDay() { + ledger.record("a", List.of(vote("u1", "Steve", NOW), vote("u2", "STEVE", NOW.plusSeconds(60))), NOW); + + assertEquals(1, ledger.pendingFor(STEVE).size()); + } + + @Test + void nextUtcDayEarnsAgain() { + ledger.record("a", List.of(vote("u1", "Steve", NOW)), NOW); + Instant tomorrow = NOW.plus(Duration.ofDays(1)); + + assertEquals(1, ledger.record("a", List.of(vote("u2", "Steve", tomorrow)), tomorrow).size()); + } + + @Test + void listsAreCountedSeparately() { + ledger.record("a", List.of(vote("u1", "Steve", NOW)), NOW); + ledger.record("b", List.of(vote("u2", "Steve", NOW)), NOW); + + assertEquals(2, ledger.pendingFor(STEVE).size()); + } + + @Test + void voteWithoutNicknameEarnsNothing() { + assertEquals(List.of(), ledger.record("a", List.of(vote("u1", null, NOW)), NOW)); + } + + @Test + void takingPendingRemovesItAndReturningPutsItBack() { + ledger.record("a", List.of(vote("u1", "Steve", NOW)), NOW); + + List taken = ledger.takePending(STEVE); + + assertEquals(1, taken.size()); + assertEquals(List.of(), ledger.takePending(STEVE)); + + ledger.returnPending(taken.get(0)); + ledger.returnPending(taken.get(0)); + + assertEquals(1, ledger.pendingFor(STEVE).size()); + } + + @Test + void uncollectedRewardsExpire() { + ledger.record("a", List.of(vote("u1", "Steve", NOW)), NOW); + + assertEquals(List.of(), ledger.expirePending(NOW.plus(Duration.ofDays(1)))); + assertEquals(1, ledger.expirePending(NOW.plus(VoteLedger.PENDING_EXPIRY).plusSeconds(1)).size()); + assertEquals(List.of(), ledger.pendingFor(STEVE)); + } + + @Test + void removedListsAreForgotten() { + ledger.record("a", List.of(), NOW); + ledger.record("b", List.of(), NOW); + + ledger.retainSites(Set.of("a")); + + assertEquals(Set.of("a"), ledger.snapshot().cursors().keySet()); + } + + @Test + void tracksUnsavedChanges() { + assertFalse(ledger.isDirty()); + + ledger.record("a", List.of(), NOW); + assertTrue(ledger.isDirty()); + + ledger.markSaved(); + assertFalse(ledger.isDirty()); + } + + @Test + void survivesSnapshotRoundTrip() { + ledger.record("a", List.of(vote("u1", "Steve", NOW)), NOW); + + VoteLedger restored = VoteLedger.restore(ledger.snapshot()); + + assertEquals(1, restored.pendingFor(STEVE).size()); + assertEquals(ledger.checkFrom("a", NOW), restored.checkFrom("a", NOW)); + assertEquals(List.of(), restored.record("a", List.of(vote("u1", "Steve", NOW)), NOW)); + } + + private static Vote vote(String id, String nickname, Instant castAt) { + return Vote.of(id, nickname, castAt); + } +} diff --git a/src/test/java/me/adixe/votereward/ledger/YamlLedgerRepositoryTest.java b/src/test/java/me/adixe/votereward/ledger/YamlLedgerRepositoryTest.java new file mode 100644 index 0000000..89259c5 --- /dev/null +++ b/src/test/java/me/adixe/votereward/ledger/YamlLedgerRepositoryTest.java @@ -0,0 +1,72 @@ +package me.adixe.votereward.ledger; + +import me.adixe.votereward.vote.Nickname; +import me.adixe.votereward.vote.Vote; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Instant; +import java.time.LocalDate; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class YamlLedgerRepositoryTest { + private static final Instant NOW = Instant.parse("2026-10-25T12:00:00Z"); + + @TempDir + Path folder; + + @Test + void missingFileMeansEmptyLedger() throws IOException { + assertEquals(LedgerSnapshot.EMPTY, new YamlLedgerRepository(folder.resolve("ledger.yml")).load()); + } + + @Test + void savesAndLoadsEverything() throws IOException { + Path file = folder.resolve("data").resolve("ledger.yml"); + YamlLedgerRepository repository = new YamlLedgerRepository(file); + + VoteLedger ledger = VoteLedger.empty(); + ledger.record("lista-minecraft", List.of(Vote.of("u1", "Steve", NOW)), NOW); + repository.save(ledger.snapshot()); + + assertTrue(Files.exists(file)); + assertFalse(Files.exists(file.resolveSibling("ledger.yml.tmp"))); + + LedgerSnapshot loaded = repository.load(); + assertEquals(ledger.snapshot(), loaded); + + VoteLedger restored = VoteLedger.restore(loaded); + assertEquals("Steve", restored.pendingFor(Nickname.of("steve")).get(0).nickname().value()); + assertTrue(restored.wasRewarded("lista-minecraft", Nickname.of("STEVE"), LocalDate.of(2026, 10, 25))); + } + + @Test + void readsUnquotedTimestampsFromHandEditedFiles() throws IOException { + Path file = folder.resolve("ledger.yml"); + Files.writeString(file, """ + cursors: + a: + position: 2026-10-25T12:00:00Z + recent-votes: {} + pending: [] + """); + + assertEquals(NOW, new YamlLedgerRepository(file).load().cursors().get("a").position()); + } + + @Test + void damagedFileIsReported() throws IOException { + Path file = folder.resolve("ledger.yml"); + Files.writeString(file, "cursors:\n a:\n position: not-a-date\n"); + + assertThrows(IOException.class, () -> new YamlLedgerRepository(file).load()); + } +} diff --git a/src/test/java/me/adixe/votereward/reward/RewardServiceTest.java b/src/test/java/me/adixe/votereward/reward/RewardServiceTest.java new file mode 100644 index 0000000..286aa7d --- /dev/null +++ b/src/test/java/me/adixe/votereward/reward/RewardServiceTest.java @@ -0,0 +1,103 @@ +package me.adixe.votereward.reward; + +import me.adixe.votereward.ledger.PendingReward; +import me.adixe.votereward.ledger.VoteLedger; +import me.adixe.votereward.site.VoteSites; +import me.adixe.votereward.vote.Nickname; +import me.adixe.votereward.vote.Vote; +import org.junit.jupiter.api.Test; + +import java.time.Instant; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.function.Consumer; +import java.util.logging.Logger; + +import static me.adixe.votereward.TestData.site; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class RewardServiceTest { + private static final Instant NOW = Instant.parse("2026-10-25T12:00:00Z"); + private static final Nickname STEVE = Nickname.of("Steve"); + + private final VoteLedger ledger = VoteLedger.empty(); + private final Set online = new HashSet<>(); + private final RecordingDispatcher dispatcher = new RecordingDispatcher(); + private final RewardService service = new RewardService(ledger, new VoteSites(List.of(site("a"))), + online::contains, dispatcher, silentLogger()); + + @Test + void deliversWaitingRewards() { + ledger.record("a", List.of(Vote.of("u1", "Steve", NOW)), NOW); + + assertEquals(1, service.deliver(STEVE)); + assertEquals(1, dispatcher.given.size()); + assertEquals("a", dispatcher.given.get(0).site().name()); + assertEquals(List.of(), ledger.pendingFor(STEVE)); + } + + @Test + void nothingToDeliver() { + assertEquals(0, service.deliver(STEVE)); + assertTrue(dispatcher.given.isEmpty()); + } + + @Test + void newRewardsGoStraightToOnlinePlayers() { + online.add(STEVE); + + service.rewardsEarned(ledger.record("a", List.of(Vote.of("u1", "Steve", NOW)), NOW)); + + assertEquals(1, dispatcher.given.size()); + } + + @Test + void offlinePlayersKeepTheirRewardForLater() { + service.rewardsEarned(ledger.record("a", List.of(Vote.of("u1", "Steve", NOW)), NOW)); + + assertTrue(dispatcher.given.isEmpty()); + assertEquals(1, ledger.pendingFor(STEVE).size()); + } + + @Test + void rewardThatCouldNotBeGivenWaitsAgain() { + ledger.record("a", List.of(Vote.of("u1", "Steve", NOW)), NOW); + dispatcher.playerLeft = true; + + service.deliver(STEVE); + + assertEquals(1, ledger.pendingFor(STEVE).size()); + } + + @Test + void rewardForARemovedListIsDropped() { + ledger.record("removed", List.of(Vote.of("u1", "Steve", NOW)), NOW); + + assertEquals(0, service.deliver(STEVE)); + assertEquals(List.of(), ledger.pendingFor(STEVE)); + } + + private static Logger silentLogger() { + Logger logger = Logger.getAnonymousLogger(); + logger.setUseParentHandlers(false); + + return logger; + } + + private static final class RecordingDispatcher implements RewardDispatcher { + final List given = new ArrayList<>(); + boolean playerLeft; + + @Override + public void dispatch(Nickname player, List rewards, Consumer undelivered) { + if (playerLeft) { + rewards.forEach(reward -> undelivered.accept(reward.pending())); + } else { + given.addAll(rewards); + } + } + } +} diff --git a/src/test/java/me/adixe/votereward/reward/VotePollerTest.java b/src/test/java/me/adixe/votereward/reward/VotePollerTest.java new file mode 100644 index 0000000..96dd38a --- /dev/null +++ b/src/test/java/me/adixe/votereward/reward/VotePollerTest.java @@ -0,0 +1,156 @@ +package me.adixe.votereward.reward; + +import me.adixe.votereward.api.VoteSource; +import me.adixe.votereward.api.VoteSourceException; +import me.adixe.votereward.config.Settings; +import me.adixe.votereward.ledger.LedgerRepository; +import me.adixe.votereward.ledger.LedgerSnapshot; +import me.adixe.votereward.ledger.VoteLedger; +import me.adixe.votereward.site.VoteSite; +import me.adixe.votereward.site.VoteSites; +import me.adixe.votereward.vote.Nickname; +import me.adixe.votereward.vote.Vote; +import org.junit.jupiter.api.Test; + +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.logging.Handler; +import java.util.logging.Level; +import java.util.logging.LogRecord; +import java.util.logging.Logger; + +import static me.adixe.votereward.TestData.site; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +class VotePollerTest { + private static final Instant NOW = Instant.parse("2026-10-25T12:00:00Z"); + + private final VoteLedger ledger = VoteLedger.empty(); + private final FakeSource source = new FakeSource(); + private final SavingRepository repository = new SavingRepository(); + private final List rewarded = new ArrayList<>(); + private final List logs = new ArrayList<>(); + private final Logger logger = Logger.getAnonymousLogger(); + + VotePollerTest() { + logger.setUseParentHandlers(false); + logger.addHandler(new Handler() { + @Override + public void publish(LogRecord record) { + logs.add(record); + } + + @Override + public void flush() { + } + + @Override + public void close() { + } + }); + } + + @Test + void checksEveryListFromItsCursorAndRewardsOnlinePlayers() { + source.votes.put("a", List.of(Vote.of("u1", "Steve", NOW.minusSeconds(10)))); + source.votes.put("b", List.of()); + + PollReport report = poller(site("a"), site("b", "https://b.pl")).poll(); + + assertEquals(new PollReport(2, 0, 1, 1, false), report); + assertEquals(NOW.minus(VoteLedger.INITIAL_LOOKBACK), source.asked.get("a")); + assertEquals(List.of(Nickname.of("Steve")), rewarded); + assertEquals(1, repository.saves); + } + + @Test + void oneFailingListDoesNotStopTheOthers() { + source.votes.put("b", List.of(Vote.of("u1", "Steve", NOW))); + + PollReport report = poller(site("a"), site("b", "https://b.pl")).poll(); + + assertEquals(1, report.sitesChecked()); + assertEquals(1, report.sitesFailed()); + assertEquals(1, report.rewardsEarned()); + } + + @Test + void failingListIsLoggedOnceUntilItRecovers() { + VotePoller poller = poller(site("a")); + + poller.poll(); + poller.poll(); + assertEquals(1, logs.stream().filter(log -> log.getLevel() == Level.WARNING).count()); + + source.votes.put("a", List.of()); + poller.poll(); + assertEquals(1, logs.stream().filter(log -> log.getLevel() == Level.INFO).count()); + } + + @Test + void failedListKeepsItsPositionSoNoVoteIsMissed() { + VotePoller poller = poller(site("a")); + + poller.poll(); + poller.poll(); + + assertNull(ledger.snapshot().cursors().get("a")); + } + + @Test + void doesNotSaveWhenNothingChanged() { + VotePoller poller = poller(site("a")); + + poller.poll(); + + assertEquals(0, repository.saves); + } + + private VotePoller poller(VoteSite... sites) { + VoteSites voteSites = new VoteSites(List.of(sites)); + RewardService rewards = new RewardService(ledger, voteSites, nickname -> true, + (player, given, undelivered) -> rewarded.add(player), logger); + + return new VotePoller(new Settings(Duration.ofSeconds(30), voteSites), source, ledger, repository, rewards, + Clock.fixed(NOW, ZoneOffset.UTC), logger); + } + + /** Lists without prepared votes fail, like an unreachable list. */ + private static final class FakeSource implements VoteSource { + final Map> votes = new HashMap<>(); + final Map asked = new HashMap<>(); + + @Override + public List votesSince(VoteSite site, Instant since) throws VoteSourceException { + asked.put(site.name(), since); + List result = votes.get(site.name()); + + if (result == null) { + throw new VoteSourceException("unreachable"); + } + + return result; + } + } + + private static final class SavingRepository implements LedgerRepository { + int saves; + + @Override + public LedgerSnapshot load() { + return LedgerSnapshot.EMPTY; + } + + @Override + public void save(LedgerSnapshot snapshot) { + saves++; + } + } +} diff --git a/src/test/java/me/adixe/votereward/site/ListAddressTest.java b/src/test/java/me/adixe/votereward/site/ListAddressTest.java new file mode 100644 index 0000000..52520f6 --- /dev/null +++ b/src/test/java/me/adixe/votereward/site/ListAddressTest.java @@ -0,0 +1,37 @@ +package me.adixe.votereward.site; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class ListAddressTest { + @Test + void stripsTrailingSlashes() { + assertEquals("https://lista-minecraft.pl", ListAddress.of("https://lista-minecraft.pl//").toString()); + } + + @Test + void resolvesApiPaths() { + assertEquals("https://lista-minecraft.pl/api/v1/servers/x/votes", + ListAddress.of("https://lista-minecraft.pl/").resolve("/api/v1/servers/x/votes").toString()); + } + + @Test + void acceptsHttpForLocalDevelopment() { + assertEquals("localhost", ListAddress.of("http://localhost:8080").host()); + } + + @Test + void rejectsInvalidAddresses() { + assertThrows(IllegalArgumentException.class, () -> ListAddress.of("lista-minecraft.pl")); + assertThrows(IllegalArgumentException.class, () -> ListAddress.of("ftp://lista-minecraft.pl")); + assertThrows(IllegalArgumentException.class, () -> ListAddress.of("https://lista-minecraft.pl/?a=b")); + assertThrows(IllegalArgumentException.class, () -> ListAddress.of("")); + } + + @Test + void equalByAddress() { + assertEquals(ListAddress.of("https://a.pl/"), ListAddress.of("https://a.pl")); + } +} diff --git a/src/test/java/me/adixe/votereward/site/RewardCommandTest.java b/src/test/java/me/adixe/votereward/site/RewardCommandTest.java new file mode 100644 index 0000000..8f43dec --- /dev/null +++ b/src/test/java/me/adixe/votereward/site/RewardCommandTest.java @@ -0,0 +1,37 @@ +package me.adixe.votereward.site; + +import me.adixe.votereward.text.Placeholders; +import me.adixe.votereward.vote.ServerId; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class RewardCommandTest { + @Test + void rendersPlaceholders() { + RewardCommand command = new RewardCommand("give %player_name% diamond %player_name%"); + + assertEquals("give Steve diamond Steve", command.render(Placeholders.of("player_name", "Steve"))); + } + + @Test + void dropsLeadingSlashBecauseTheConsoleDoesNotUseIt() { + assertEquals("say hi", new RewardCommand(" /say hi ").template()); + } + + @Test + void rejectsEmpty() { + assertThrows(IllegalArgumentException.class, () -> new RewardCommand(" ")); + } + + @Test + void sitesMustHaveUniqueNames() { + VoteSite site = new VoteSite("a", ListAddress.of("https://a.pl"), + ServerId.of("183413bc-4588-4265-8f06-346963e5d7df"), List.of()); + + assertThrows(IllegalArgumentException.class, () -> new VoteSites(List.of(site, site))); + } +} diff --git a/src/test/java/me/adixe/votereward/text/PlaceholdersTest.java b/src/test/java/me/adixe/votereward/text/PlaceholdersTest.java new file mode 100644 index 0000000..c82618c --- /dev/null +++ b/src/test/java/me/adixe/votereward/text/PlaceholdersTest.java @@ -0,0 +1,27 @@ +package me.adixe.votereward.text; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class PlaceholdersTest { + @Test + void replacesKnownAndLeavesUnknown() { + Placeholders placeholders = Placeholders.of("a", 1).with("b", "two"); + + assertEquals("1 two %c%", placeholders.apply("%a% %b% %c%")); + } + + @Test + void isImmutable() { + Placeholders base = Placeholders.of("a", 1); + base.with("a", 2); + + assertEquals("1", base.apply("%a%")); + } + + @Test + void mergesWithLaterValuesWinning() { + assertEquals("2", Placeholders.of("a", 1).with(Placeholders.of("a", 2)).apply("%a%")); + } +} diff --git a/src/test/java/me/adixe/votereward/vote/NicknameTest.java b/src/test/java/me/adixe/votereward/vote/NicknameTest.java new file mode 100644 index 0000000..807ebef --- /dev/null +++ b/src/test/java/me/adixe/votereward/vote/NicknameTest.java @@ -0,0 +1,30 @@ +package me.adixe.votereward.vote; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class NicknameTest { + @Test + void equalityIgnoresLetterCase() { + assertEquals(Nickname.of("Steve"), Nickname.of("sTEVE")); + assertEquals(Nickname.of("Steve").hashCode(), Nickname.of("steve").hashCode()); + assertNotEquals(Nickname.of("Steve"), Nickname.of("Alex")); + } + + @Test + void keepsTheOriginalSpellingAndTrimsSpaces() { + Nickname nickname = Nickname.of(" Steve_01 "); + + assertEquals("Steve_01", nickname.value()); + assertEquals("steve_01", nickname.key()); + } + + @Test + void rejectsBlank() { + assertThrows(IllegalArgumentException.class, () -> Nickname.of(" ")); + assertThrows(IllegalArgumentException.class, () -> Nickname.of(null)); + } +} diff --git a/src/test/java/me/adixe/votereward/vote/ServerIdTest.java b/src/test/java/me/adixe/votereward/vote/ServerIdTest.java new file mode 100644 index 0000000..1208098 --- /dev/null +++ b/src/test/java/me/adixe/votereward/vote/ServerIdTest.java @@ -0,0 +1,21 @@ +package me.adixe.votereward.vote; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class ServerIdTest { + @Test + void parsesUuid() { + assertEquals("183413bc-4588-4265-8f06-346963e5d7df", + ServerId.of(" 183413bc-4588-4265-8f06-346963e5d7df ").toString()); + } + + @Test + void rejectsAnythingElse() { + assertThrows(IllegalArgumentException.class, () -> ServerId.of("not-a-uuid")); + assertThrows(IllegalArgumentException.class, () -> ServerId.of("")); + assertThrows(IllegalArgumentException.class, () -> ServerId.of(null)); + } +} diff --git a/src/test/java/me/adixe/votereward/vote/VoteTest.java b/src/test/java/me/adixe/votereward/vote/VoteTest.java new file mode 100644 index 0000000..f0b504e --- /dev/null +++ b/src/test/java/me/adixe/votereward/vote/VoteTest.java @@ -0,0 +1,31 @@ +package me.adixe.votereward.vote; + +import org.junit.jupiter.api.Test; + +import java.time.Instant; +import java.time.LocalDate; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class VoteTest { + private static final Instant NOW = Instant.parse("2026-10-25T09:00:00Z"); + + @Test + void voteWithoutNicknameHasNone() { + assertTrue(Vote.of("id", null, NOW).nickname().isEmpty()); + assertTrue(Vote.of("id", " ", NOW).nickname().isEmpty()); + } + + @Test + void voteNeedsAnId() { + assertThrows(IllegalArgumentException.class, () -> Vote.of("", "Steve", NOW)); + } + + @Test + void voteDayIsTheUtcDate() { + assertEquals(LocalDate.of(2026, 10, 25), VoteDay.of(Instant.parse("2026-10-25T23:59:59Z"))); + assertEquals(LocalDate.of(2026, 10, 26), VoteDay.of(Instant.parse("2026-10-26T00:00:00Z"))); + } +}