diff --git a/Mimante/.dockerignore b/Mimante/.dockerignore new file mode 100644 index 0000000..505da9a --- /dev/null +++ b/Mimante/.dockerignore @@ -0,0 +1,17 @@ +# Ciò che non serve nel contesto di build dell'immagine. +.git +.gitignore +.gitattributes +.vscode +.claude +.gitea +**/bin +**/obj +**/TestResults +out +legacy +docs +tools +unraid +*.md +Modifiche.txt diff --git a/Mimante/.gitattributes b/Mimante/.gitattributes new file mode 100644 index 0000000..78964d5 --- /dev/null +++ b/Mimante/.gitattributes @@ -0,0 +1,11 @@ +# I file che finiscono nel container o sul runner Linux restano LF anche su Windows: +# uno script con CRLF nel shebang non parte ("bad interpreter"). +*.sh text eol=lf +*.sql text eol=lf +*.yml text eol=lf +*.yaml text eol=lf +Dockerfile text eol=lf +*.xml text eol=lf + +*.png binary +*.ico binary diff --git a/Mimante/.gitea/workflows/rilascio.yml b/Mimante/.gitea/workflows/rilascio.yml new file mode 100644 index 0000000..0145e79 --- /dev/null +++ b/Mimante/.gitea/workflows/rilascio.yml @@ -0,0 +1,55 @@ +# Rilascio a ogni tag vX.Y.Z: controlla che il tag coincida con di +# Directory.Build.props, costruisce e pubblica l'immagine sul registry del Gitea +# (192.168.30.23:3000/alby96/bidoo-bidbot:X.Y.Z e :latest), poi crea la release con la +# sezione del CHANGELOG e il template Unraid allegato. +# +# Segreti del repository: REGISTRY_USER e REGISTRY_TOKEN (token con package: read and +# write e repository: read and write). Il registry è in HTTP: il demone Docker del runner +# (quello di Unraid, se il runner monta il suo socket) deve averlo fra gli insecure-registries. +name: Rilascio + +on: + push: + tags: ['v*'] + +jobs: + immagine: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Versione coerente con il tag + run: | + V=$(sed -n 's/.*\(.*\)<\/Version>.*/\1/p' Directory.Build.props) + [ "v$V" = "${GITHUB_REF_NAME}" ] || { echo "tag ${GITHUB_REF_NAME} diverso da $V"; exit 1; } + echo "VERSION=$V" >> "$GITHUB_ENV" + + - name: Login al registry + run: echo "${{ secrets.REGISTRY_TOKEN }}" | docker login 192.168.30.23:3000 -u "${{ secrets.REGISTRY_USER }}" --password-stdin + + - name: Costruzione e pubblicazione dell'immagine + run: | + IMG=192.168.30.23:3000/alby96/bidoo-bidbot + docker build -f docker/Dockerfile \ + --build-arg VERSION=$VERSION \ + --build-arg GIT_COMMIT="${GITHUB_SHA::12}" \ + -t $IMG:$VERSION -t $IMG:latest . + docker push $IMG:$VERSION + docker push $IMG:latest + + - name: Release su Gitea con il template Unraid + env: + TOKEN: ${{ secrets.REGISTRY_TOKEN }} + API: ${{ github.server_url }}/api/v1/repos/${{ github.repository }} + run: | + set -eu + NOTE=$(awk -v v="$VERSION" '/^## /{p=($2==v)} p' CHANGELOG.md) + [ -n "$NOTE" ] || NOTE="Versione $VERSION" + ID=$(curl -sf -H "Authorization: token $TOKEN" "$API/releases/tags/${GITHUB_REF_NAME}" | jq -r '.id // empty' || true) + if [ -z "$ID" ]; then + ID=$(curl -sf -X POST "$API/releases" \ + -H "Authorization: token $TOKEN" -H "Content-Type: application/json" \ + -d "$(jq -n --arg t "$GITHUB_REF_NAME" --arg n "$NOTE" '{tag_name:$t, name:("Bidoo BidBot " + $t), body:$n}')" | jq -r .id) + fi + curl -sf -X POST "$API/releases/$ID/assets?name=bidoo-bidbot.xml" \ + -H "Authorization: token $TOKEN" -F attachment=@unraid/bidoo-bidbot.xml > /dev/null diff --git a/Mimante/.gitea/workflows/verifica.yml b/Mimante/.gitea/workflows/verifica.yml index d6baedf..1bc14ed 100644 --- a/Mimante/.gitea/workflows/verifica.yml +++ b/Mimante/.gitea/workflows/verifica.yml @@ -1,3 +1,8 @@ +# Verifica a ogni push su main e a ogni pull request: compilazione con gli avvisi come +# errori e tutti i test, compresi quelli su PostgreSQL 18 (servizio del job). +# +# Serve un runner Linux con Docker e l'etichetta ubuntu-latest: se non c'è, il README +# (sezione «Sviluppo») spiega come registrarne uno su Unraid con gitea/act_runner. name: Verifica on: @@ -7,26 +12,43 @@ on: jobs: test: - runs-on: windows + runs-on: ubuntu-latest + services: + postgres: + image: postgres:18 + env: + POSTGRES_PASSWORD: test + POSTGRES_USER: admin + POSTGRES_DB: bidbot_test + ports: ["5432:5432"] + options: >- + --health-cmd "pg_isready -U admin -d bidbot_test" + --health-interval 5s + --health-retries 10 steps: - - name: Sorgenti - uses: actions/checkout@v4 + - uses: actions/checkout@v4 - - name: .NET 10 - uses: actions/setup-dotnet@v4 + - uses: actions/setup-dotnet@v4 with: dotnet-version: '10.0.x' - name: Compila - run: dotnet build Tests/AutoBidder.Tests.csproj -c Debug --nologo -v q --artifacts-path "${{ runner.temp }}/AutoBidder.Verifica" + run: dotnet build BidooBidBot.sln -c Release --nologo - name: Test - run: dotnet test Tests/AutoBidder.Tests.csproj -c Debug --no-build --nologo --artifacts-path "${{ runner.temp }}/AutoBidder.Verifica" --logger "trx;LogFileName=risultati.trx" + env: + TEST_DB_HOST: postgres + TEST_DB_USER: admin + TEST_DB_PASSWORD: test + TEST_DB_NAME: bidbot_test + run: >- + dotnet test tests/BidooBidBot.Tests -c Release --no-build --nologo + --logger "trx;LogFileName=risultati.trx" --results-directory out/test - name: Risultati if: always() uses: actions/upload-artifact@v4 with: name: risultati-test - path: ${{ runner.temp }}/AutoBidder.Verifica/**/*.trx + path: out/test/*.trx if-no-files-found: ignore diff --git a/Mimante/.gitignore b/Mimante/.gitignore new file mode 100644 index 0000000..645acae --- /dev/null +++ b/Mimante/.gitignore @@ -0,0 +1,5 @@ +# Bidoo BidBot: dati delle prove locali e risultati +tools/dev/config/ +tools/dev/config-simulatore/ +out/ +*.trx diff --git a/Mimante/BidooBidBot.sln b/Mimante/BidooBidBot.sln new file mode 100644 index 0000000..0c90574 --- /dev/null +++ b/Mimante/BidooBidBot.sln @@ -0,0 +1,56 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.0.31903.59 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{827E0CD3-B72D-47B6-A68D-7590B98EB39B}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BidooBidBot", "src\BidooBidBot\BidooBidBot.csproj", "{5CA3665D-BD05-4811-B099-12CB5BE6D9B9}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{0AB3BF05-4346-4AA6-1389-037BE0695223}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BidooBidBot.Tests", "tests\BidooBidBot.Tests\BidooBidBot.Tests.csproj", "{1C5980F7-E3CB-4999-AB1D-4B6F5FAAB217}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|Any CPU = Release|Any CPU + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {5CA3665D-BD05-4811-B099-12CB5BE6D9B9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {5CA3665D-BD05-4811-B099-12CB5BE6D9B9}.Debug|Any CPU.Build.0 = Debug|Any CPU + {5CA3665D-BD05-4811-B099-12CB5BE6D9B9}.Debug|x64.ActiveCfg = Debug|Any CPU + {5CA3665D-BD05-4811-B099-12CB5BE6D9B9}.Debug|x64.Build.0 = Debug|Any CPU + {5CA3665D-BD05-4811-B099-12CB5BE6D9B9}.Debug|x86.ActiveCfg = Debug|Any CPU + {5CA3665D-BD05-4811-B099-12CB5BE6D9B9}.Debug|x86.Build.0 = Debug|Any CPU + {5CA3665D-BD05-4811-B099-12CB5BE6D9B9}.Release|Any CPU.ActiveCfg = Release|Any CPU + {5CA3665D-BD05-4811-B099-12CB5BE6D9B9}.Release|Any CPU.Build.0 = Release|Any CPU + {5CA3665D-BD05-4811-B099-12CB5BE6D9B9}.Release|x64.ActiveCfg = Release|Any CPU + {5CA3665D-BD05-4811-B099-12CB5BE6D9B9}.Release|x64.Build.0 = Release|Any CPU + {5CA3665D-BD05-4811-B099-12CB5BE6D9B9}.Release|x86.ActiveCfg = Release|Any CPU + {5CA3665D-BD05-4811-B099-12CB5BE6D9B9}.Release|x86.Build.0 = Release|Any CPU + {1C5980F7-E3CB-4999-AB1D-4B6F5FAAB217}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {1C5980F7-E3CB-4999-AB1D-4B6F5FAAB217}.Debug|Any CPU.Build.0 = Debug|Any CPU + {1C5980F7-E3CB-4999-AB1D-4B6F5FAAB217}.Debug|x64.ActiveCfg = Debug|Any CPU + {1C5980F7-E3CB-4999-AB1D-4B6F5FAAB217}.Debug|x64.Build.0 = Debug|Any CPU + {1C5980F7-E3CB-4999-AB1D-4B6F5FAAB217}.Debug|x86.ActiveCfg = Debug|Any CPU + {1C5980F7-E3CB-4999-AB1D-4B6F5FAAB217}.Debug|x86.Build.0 = Debug|Any CPU + {1C5980F7-E3CB-4999-AB1D-4B6F5FAAB217}.Release|Any CPU.ActiveCfg = Release|Any CPU + {1C5980F7-E3CB-4999-AB1D-4B6F5FAAB217}.Release|Any CPU.Build.0 = Release|Any CPU + {1C5980F7-E3CB-4999-AB1D-4B6F5FAAB217}.Release|x64.ActiveCfg = Release|Any CPU + {1C5980F7-E3CB-4999-AB1D-4B6F5FAAB217}.Release|x64.Build.0 = Release|Any CPU + {1C5980F7-E3CB-4999-AB1D-4B6F5FAAB217}.Release|x86.ActiveCfg = Release|Any CPU + {1C5980F7-E3CB-4999-AB1D-4B6F5FAAB217}.Release|x86.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {5CA3665D-BD05-4811-B099-12CB5BE6D9B9} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} + {1C5980F7-E3CB-4999-AB1D-4B6F5FAAB217} = {0AB3BF05-4346-4AA6-1389-037BE0695223} + EndGlobalSection +EndGlobal diff --git a/Mimante/Directory.Build.props b/Mimante/Directory.Build.props new file mode 100644 index 0000000..b32c64b --- /dev/null +++ b/Mimante/Directory.Build.props @@ -0,0 +1,40 @@ + + + + + 1.0.0 + Bidoo BidBot + Alberto Balbo + Uso personale + + + + net10.0 + latest + enable + enable + true + true + it-IT + it + + + + + false + true + true + false + + + diff --git a/Mimante/docker/Dockerfile b/Mimante/docker/Dockerfile new file mode 100644 index 0000000..e00d48d --- /dev/null +++ b/Mimante/docker/Dockerfile @@ -0,0 +1,97 @@ +# syntax=docker/dockerfile:1.7 +# +# Bidoo BidBot: un solo container con motore, interfaccia web e Chromium per l'accesso +# assistito a Bidoo. +# +# docker build -f docker/Dockerfile --build-arg VERSION=1.0.0 --build-arg GIT_COMMIT=$(git rev-parse --short=12 HEAD) -t bidoo-bidbot:1.0.0 . +# +# Stadi: build (restore + compilazione), test (i test di logica pura; quelli su PostgreSQL +# saltano da soli senza TEST_DB_HOST), publish (ReadyToRun per linux-x64), runtime. +# +# Il runtime è Debian 13 con il runtime ASP.NET copiato dall'immagine ufficiale: per .NET 10 +# Microsoft pubblica solo immagini Ubuntu/Alpine/Azure Linux, e su Ubuntu «apt install +# chromium» installa soltanto il rimando a snap, che in un container non funziona. Su Debian +# il pacchetto chromium è il browser vero (docs/adr/0010-immagine-debian-con-runtime-copiato.md). + +ARG DOTNET_VERSION=10.0 + +# ─────────────────────────────────────────────────────────────── build +FROM mcr.microsoft.com/dotnet/sdk:${DOTNET_VERSION} AS build +WORKDIR /src + +COPY Directory.Build.props BidooBidBot.sln ./ +COPY src/BidooBidBot/BidooBidBot.csproj src/BidooBidBot/ +COPY tests/BidooBidBot.Tests/BidooBidBot.Tests.csproj tests/BidooBidBot.Tests/ +RUN dotnet restore src/BidooBidBot/BidooBidBot.csproj -r linux-x64 \ + && dotnet restore tests/BidooBidBot.Tests/BidooBidBot.Tests.csproj + +COPY src/ src/ +COPY tests/ tests/ +RUN dotnet build tests/BidooBidBot.Tests/BidooBidBot.Tests.csproj -c Release --no-restore -nologo + +# ─────────────────────────────────────────────────────────────── test +FROM build AS test +RUN dotnet test tests/BidooBidBot.Tests/BidooBidBot.Tests.csproj -c Release --no-build --nologo -v q \ + && touch /tmp/test-ok + +# ─────────────────────────────────────────────────────────────── publish +FROM build AS publish +# La publish parte solo con i test verdi. +COPY --from=test /tmp/test-ok /tmp/test-ok +RUN dotnet publish src/BidooBidBot/BidooBidBot.csproj -c Release -r linux-x64 --self-contained false \ + -p:PublishReadyToRun=true -nologo -o /app + +# ─────────────────────────────────────────────────────────────── runtime ASP.NET +FROM mcr.microsoft.com/dotnet/aspnet:${DOTNET_VERSION} AS dotnet + +# ─────────────────────────────────────────────────────────────── runtime +FROM debian:trixie-slim AS runtime +ARG VERSION=dev +ARG GIT_COMMIT=n/d + +LABEL org.opencontainers.image.title="bidoo-bidbot" \ + org.opencontainers.image.description="Bidoo BidBot: segue le aste al centesimo di Bidoo, decide con un modello appreso se puntare. Parte in modalità OSSERVA." \ + org.opencontainers.image.version="${VERSION}" \ + org.opencontainers.image.revision="${GIT_COMMIT}" \ + org.opencontainers.image.authors="Alberto Balbo" \ + org.opencontainers.image.source="http://192.168.30.23:3000/Alby96/bidoo-bidbot" + +# Dipendenze del runtime .NET (ICU, OpenSSL, zlib), fuso orario, certificati, Chromium con +# i caratteri per l'accesso assistito, setpriv (util-linux) per scendere a PUID/PGID. +RUN apt-get update \ + && apt-get install -y --no-install-recommends \ + ca-certificates tzdata libicu76 libssl3t64 libstdc++6 zlib1g libgcc-s1 \ + chromium fonts-liberation util-linux \ + && rm -rf /var/lib/apt/lists/* + +COPY --from=dotnet /usr/share/dotnet /usr/share/dotnet +RUN ln -s /usr/share/dotnet/dotnet /usr/bin/dotnet + +ENV DOTNET_ROOT=/usr/share/dotnet \ + DOTNET_gcServer=0 \ + DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=0 \ + DOTNET_NOLOGO=1 \ + ASPNETCORE_URLS= \ + ASPNETCORE_HTTP_PORTS= \ + PORT=8080 \ + TZ=Europe/Rome \ + PUID=99 \ + PGID=100 + +WORKDIR /app +COPY --from=publish /app ./ +COPY docker/entrypoint.sh /entrypoint.sh +RUN sed -i 's/\r$//' /entrypoint.sh && chmod +x /entrypoint.sh && mkdir -p /config + +VOLUME ["/config"] +EXPOSE 8080 + +# /salute risponde 200 solo con configurazione e database a posto. Nell'immagine non c'è +# curl: la sonda è il programma stesso con --salute. +HEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \ + CMD ["dotnet", "/app/BidooBidBot.dll", "--salute"] + +# SIGTERM arriva al processo dotnet (exec nell'entrypoint): spegnimento ordinato in 10 s. +STOPSIGNAL SIGTERM +ENTRYPOINT ["/entrypoint.sh"] +CMD ["dotnet", "/app/BidooBidBot.dll"] diff --git a/Mimante/docker/entrypoint.sh b/Mimante/docker/entrypoint.sh new file mode 100644 index 0000000..951ca3f --- /dev/null +++ b/Mimante/docker/entrypoint.sh @@ -0,0 +1,42 @@ +#!/bin/sh +# Bidoo BidBot: entrypoint del container. +# +# 1. Fuso orario da TZ (tzdata è nell'immagine). +# 2. Utente e gruppo da PUID/PGID (predefiniti 99/100, «nobody:users» di Unraid): /config +# passa a quell'utente, così i file scritti dal bot si leggono dalla share appdata. +# 3. exec del processo finale con setpriv: PID 1 è dotnet e SIGTERM arriva a lui. +# +# Con PUID=0 il bot resta root: sconsigliato, ammesso per il debug. +set -eu + +PUID="${PUID:-99}" +PGID="${PGID:-100}" + +if [ -n "${TZ:-}" ] && [ -f "/usr/share/zoneinfo/${TZ}" ]; then + ln -sf "/usr/share/zoneinfo/${TZ}" /etc/localtime + echo "${TZ}" > /etc/timezone +fi + +mkdir -p /config + +if [ "${PUID}" = "0" ]; then + echo "bidoo-bidbot: avvio come root (PUID=0), fuso ${TZ:-UTC}" + exec "$@" +fi + +if ! getent group "${PGID}" >/dev/null 2>&1; then + groupadd -g "${PGID}" bidbot +fi +GROUP_NAME="$(getent group "${PGID}" | cut -d: -f1)" + +if ! getent passwd "${PUID}" >/dev/null 2>&1; then + useradd -r -o -u "${PUID}" -g "${PGID}" -M -d /config -s /usr/sbin/nologin bidbot +fi + +chown -R "${PUID}:${PGID}" /config + +# Chromium vuole una home scrivibile per la cache: la sua sta dentro /config/browser. +export HOME=/config + +echo "bidoo-bidbot: avvio come uid ${PUID} gid ${PGID} (${GROUP_NAME}), fuso ${TZ:-UTC}" +exec setpriv --reuid="${PUID}" --regid="${PGID}" --init-groups "$@" diff --git a/Mimante/src/BidooBidBot/AppInfo.cs b/Mimante/src/BidooBidBot/AppInfo.cs new file mode 100644 index 0000000..f26c5c3 --- /dev/null +++ b/Mimante/src/BidooBidBot/AppInfo.cs @@ -0,0 +1,31 @@ +using System.Globalization; +using System.Reflection; + +namespace BidooBidBot; + +/// Versione e identità del programma, da Directory.Build.props. +public static class AppInfo +{ + public const string Name = "Bidoo BidBot"; + + /// MAJOR.MINOR.PATCH, senza l'hash del commit che il compilatore aggiunge dopo il «+». + public static string Version { get; } = ReadVersion(); + + public static readonly CultureInfo Italian = CultureInfo.GetCultureInfo("it-IT"); + + /// Il fuso con cui si mostrano gli orari (TZ del container, di solito Europe/Rome). + public static TimeZoneInfo TimeZone { get; set; } = TimeZoneInfo.Local; + + public static DateTime LocalNow => TimeZoneInfo.ConvertTime(DateTime.UtcNow, TimeZone); + + public static DateTime ToLocal(DateTime utc) => + TimeZoneInfo.ConvertTime(utc.Kind == DateTimeKind.Utc ? utc : DateTime.SpecifyKind(utc, DateTimeKind.Utc), TimeZone); + + private static string ReadVersion() + { + var info = typeof(AppInfo).Assembly.GetCustomAttribute()?.InformationalVersion; + if (string.IsNullOrEmpty(info)) return typeof(AppInfo).Assembly.GetName().Version?.ToString(3) ?? "0.0.0"; + var plus = info.IndexOf('+'); + return plus > 0 ? info[..plus] : info; + } +} diff --git a/Mimante/src/BidooBidBot/Bidoo/bidoo.default.json b/Mimante/src/BidooBidBot/Bidoo/bidoo.default.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/Mimante/src/BidooBidBot/Bidoo/bidoo.default.json @@ -0,0 +1 @@ +{} diff --git a/Mimante/src/BidooBidBot/BidooBidBot.csproj b/Mimante/src/BidooBidBot/BidooBidBot.csproj new file mode 100644 index 0000000..7a39cbc --- /dev/null +++ b/Mimante/src/BidooBidBot/BidooBidBot.csproj @@ -0,0 +1,27 @@ + + + + Exe + BidooBidBot + BidooBidBot + + false + + + + + + + + + + + + + + + + + + + diff --git a/Mimante/src/BidooBidBot/Config/ConfigPaths.cs b/Mimante/src/BidooBidBot/Config/ConfigPaths.cs new file mode 100644 index 0000000..d9019ff --- /dev/null +++ b/Mimante/src/BidooBidBot/Config/ConfigPaths.cs @@ -0,0 +1,64 @@ +namespace BidooBidBot.Config; + +/// +/// Le cartelle dentro /config (volume appdata di Unraid): file che non servono +/// in fretta o che l'utente può voler leggere o correggere a mano. +/// +public sealed class ConfigPaths +{ + public string Root { get; } + + public ConfigPaths(string root) => Root = root; + + /// Cookie di Bidoo cifrati, chiave, segreto dei cookie dell'interfaccia. + public string Session => Path.Combine(Root, "sessione"); + + /// bidoo.json: indirizzi ed espressioni del sito, ricaricati a caldo. + public string References => Path.Combine(Root, "riferimenti"); + + /// Registri giornalieri: applicativo e aste. + public string Logs => Path.Combine(Root, "registri"); + + public string Exports => Path.Combine(Root, "esportazioni"); + + /// Profilo di Chromium per l'accesso assistito. + public string Browser => Path.Combine(Root, "browser"); + + public string Backups => Path.Combine(Root, "backup"); + + /// Copie che servono a database fermo (impostazioni di Telegram). + public string Cache => Path.Combine(Root, "cache"); + + public string VersionFile => Path.Combine(Root, "versione.txt"); + + public void EnsureAll() + { + foreach (var dir in new[] { Root, Session, References, Logs, Exports, Browser, Backups, Cache }) + Directory.CreateDirectory(dir); + } + + /// La cartella è scrivibile? Serve alla schermata d'errore di configurazione. + public (bool Ok, string? Error) CheckWritable() + { + try + { + Directory.CreateDirectory(Root); + var probe = Path.Combine(Root, $".prova-{Environment.ProcessId}"); + File.WriteAllText(probe, "ok"); + File.Delete(probe); + return (true, null); + } + catch (Exception ex) + { + return (false, ex.Message); + } + } + + /// Permessi 0600 su Linux per i file con segreti; su Windows non fa nulla. + public static void RestrictToOwner(string file) + { + if (OperatingSystem.IsWindows()) return; + try { File.SetUnixFileMode(file, UnixFileMode.UserRead | UnixFileMode.UserWrite); } + catch { /* file system che non supporta i permessi: si accetta */ } + } +} diff --git a/Mimante/src/BidooBidBot/Config/EnvConfig.cs b/Mimante/src/BidooBidBot/Config/EnvConfig.cs new file mode 100644 index 0000000..d575023 --- /dev/null +++ b/Mimante/src/BidooBidBot/Config/EnvConfig.cs @@ -0,0 +1,97 @@ +using System.Globalization; +using BidooBidBot.Data; + +namespace BidooBidBot.Config; + +/// +/// La configurazione del container: solo le variabili della specifica (§10.1). Tutto il +/// resto vive nel database (impostazioni) o in /config. +/// +/// Obbligatorie DB_HOST, DB_PASSWORD, UI_PASSWORD; facoltative +/// DB_USER (admin), DB_NAME (autobidder), DB_PORT (5432), PORT +/// (8080), TZ, PUID/PGID (le usa l'entrypoint). Le password non escono +/// mai da qui: non le contiene. +/// +public sealed class EnvConfig +{ + public string? DbHostRaw { get; init; } + public string DbHost { get; init; } = ""; + public int DbPort { get; init; } = 5432; + public string DbUser { get; init; } = "admin"; + public string DbName { get; init; } = "autobidder"; + public string? DbPassword { get; init; } + public string? UiPassword { get; init; } + public int HttpPort { get; init; } = 8080; + public string ConfigDir { get; init; } = "/config"; + public string TimeZone { get; init; } = "Europe/Rome"; + + public bool HasDbHost => !string.IsNullOrWhiteSpace(DbHost); + public bool HasDbPassword => !string.IsNullOrEmpty(DbPassword); + public bool HasUiPassword => !string.IsNullOrEmpty(UiPassword); + + public DbConfig ToDbConfig() => new(DbHost, DbPort, DbUser, DbPassword ?? "", DbName); + + /// Legge l'ambiente e gli argomenti (--config cartella solo per lo sviluppo). + public static EnvConfig Read(Func env, string[] args) + { + var rawHost = env("DB_HOST")?.Trim(); + var (host, portInHost) = SplitHost(rawHost); + + var port = portInHost + ?? (int.TryParse(env("DB_PORT"), NumberStyles.Integer, CultureInfo.InvariantCulture, out var p) && p is > 0 and < 65536 ? p : 5432); + + var httpPort = int.TryParse(env("PORT"), NumberStyles.Integer, CultureInfo.InvariantCulture, out var hp) && hp is > 0 and < 65536 ? hp : 8080; + + var configDir = "/config"; + for (var i = 0; i < args.Length - 1; i++) + { + if (args[i] == "--config") configDir = Path.GetFullPath(args[i + 1]); + } + + return new EnvConfig + { + DbHostRaw = rawHost, + DbHost = host, + DbPort = port, + DbUser = NonEmpty(env("DB_USER")) ?? "admin", + DbName = NonEmpty(env("DB_NAME")) ?? "autobidder", + DbPassword = env("DB_PASSWORD"), + UiPassword = env("UI_PASSWORD"), + HttpPort = httpPort, + ConfigDir = configDir, + TimeZone = NonEmpty(env("TZ")) ?? "Europe/Rome" + }; + } + + /// + /// 192.168.30.23 oppure 192.168.30.23:5432. Un indirizzo IPv6 va scritto fra + /// quadre ([::1]:5432). + /// + public static (string Host, int? Port) SplitHost(string? raw) + { + if (string.IsNullOrWhiteSpace(raw)) return ("", null); + var text = raw.Trim(); + + if (text.StartsWith('[')) + { + var close = text.IndexOf(']'); + if (close > 0) + { + var h = text[1..close]; + var rest = text[(close + 1)..]; + return rest.StartsWith(':') && int.TryParse(rest[1..], NumberStyles.Integer, CultureInfo.InvariantCulture, out var pp) ? (h, pp) : (h, null); + } + } + + var colon = text.LastIndexOf(':'); + if (colon > 0 && text.IndexOf(':') == colon && + int.TryParse(text[(colon + 1)..], NumberStyles.Integer, CultureInfo.InvariantCulture, out var port) && port is > 0 and < 65536) + { + return (text[..colon], port); + } + + return (text, null); + } + + private static string? NonEmpty(string? s) => string.IsNullOrWhiteSpace(s) ? null : s.Trim(); +} diff --git a/Mimante/src/BidooBidBot/Config/StartupCheck.cs b/Mimante/src/BidooBidBot/Config/StartupCheck.cs new file mode 100644 index 0000000..1b82e67 --- /dev/null +++ b/Mimante/src/BidooBidBot/Config/StartupCheck.cs @@ -0,0 +1,149 @@ +using System.Net.Sockets; +using BidooBidBot.Data; +using Npgsql; + +namespace BidooBidBot.Config; + +/// Una riga della schermata d'errore di configurazione. +/// Cosa si verifica, in chiaro. +/// I valori in uso (mai una password). +/// L'errore testuale, se la verifica non passa. +public sealed record CheckItem(string Key, bool Ok, string Title, string? Detail, string? Error, string? Hint = null); + +/// Esito di un giro di verifiche all'avvio. +public sealed class StartupReport +{ + public List Items { get; } = new(); + public int Attempt { get; init; } + public DateTimeOffset At { get; init; } = DateTimeOffset.Now; + public bool AllOk => Items.All(i => i.Ok); + public CheckItem? FirstProblem => Items.FirstOrDefault(i => !i.Ok); +} + +/// +/// Le verifiche all'avvio, nell'ordine della specifica (§10.3): variabili obbligatorie, +/// cartella /config, connessione a PostgreSQL, database (creato se manca e l'utente +/// può), migrazioni, partizioni. Se qualcosa non va il bot non parte: la schermata d'errore +/// mostra questo rapporto e si riprova ogni 30 secondi. +/// +public static class StartupCheck +{ + public static async Task<(StartupReport Report, Db? Db)> RunAsync(EnvConfig env, ConfigPaths paths, int attempt, CancellationToken ct) + { + var report = new StartupReport { Attempt = attempt }; + + var dbDetail = env.HasDbHost ? $"{env.DbHost}:{env.DbPort} · utente {env.DbUser} · database {env.DbName}" : null; + + report.Items.Add(env.HasDbHost + ? new CheckItem("db_host", true, "Indirizzo del database impostato (DB_HOST)", dbDetail, null) + : new CheckItem("db_host", false, "Indirizzo del database mancante (DB_HOST)", null, + "La variabile DB_HOST è vuota.", "Nel template di bidoo-bidbot scrivi DB_HOST, per esempio 192.168.30.23:5432.")); + + report.Items.Add(env.HasDbPassword + ? new CheckItem("db_password", true, "Password del database impostata (DB_PASSWORD)", null, null) + : new CheckItem("db_password", false, "Password del database mancante (DB_PASSWORD)", null, + "La variabile DB_PASSWORD è vuota.", "Nel template di bidoo-bidbot scrivi la password dell'utente PostgreSQL.")); + + report.Items.Add(env.HasUiPassword + ? new CheckItem("ui_password", true, "Password dell'interfaccia impostata (UI_PASSWORD)", null, null) + : new CheckItem("ui_password", false, "Password dell'interfaccia mancante (UI_PASSWORD)", null, + "La variabile UI_PASSWORD è vuota: l'interfaccia comanda puntate vere e non può restare aperta.", + "Nel template di bidoo-bidbot scrivi una password in UI_PASSWORD.")); + + var (writable, writeError) = paths.CheckWritable(); + var who = OperatingSystem.IsWindows() ? "" : $", utente {Environment.GetEnvironmentVariable("PUID") ?? "?"}:{Environment.GetEnvironmentVariable("PGID") ?? "?"}"; + report.Items.Add(writable + ? new CheckItem("config", true, "Cartella /config scrivibile", $"{paths.Root}{who}", null) + : new CheckItem("config", false, "Cartella /config non scrivibile", $"{paths.Root}{who}", writeError, + "Controlla il percorso della cartella dati nel template e i permessi (PUID/PGID).")); + + if (!env.HasDbHost || !env.HasDbPassword) + { + report.Items.Add(new CheckItem("database", false, "Database non verificato", dbDetail, + "Mancano indirizzo o password del database.", null)); + return (report, null); + } + + Db? db = null; + try + { + var cfg = env.ToDbConfig(); + await EnsureDatabaseAsync(cfg, ct).ConfigureAwait(false); + db = new Db(cfg); + + report.Items.Add(new CheckItem("database", true, "Database raggiungibile", dbDetail, null)); + } + catch (Exception ex) + { + if (db != null) await db.DisposeAsync().ConfigureAwait(false); + report.Items.Add(new CheckItem("database", false, "Database non raggiungibile", dbDetail, + Explain(ex, env), "Su Unraid: Docker ▸ postgresql18 ▸ avvia; poi controlla porta e password nel template di bidoo-bidbot.")); + return (report, null); + } + + try + { + var applied = await Migrations.ApplyAsync(db.Writer, ct).ConfigureAwait(false); + var version = await Migrations.CurrentVersionAsync(db).ConfigureAwait(false); + report.Items.Add(new CheckItem("migrations", true, "Schema del database aggiornato", + applied.Count > 0 ? $"versione {version}, applicate ora: {string.Join(", ", applied.Select(a => a.Name))}" : $"versione {version}", null)); + + await Partitions.EnsureAsync(db, DateTime.UtcNow).ConfigureAwait(false); + } + catch (Exception ex) + { + report.Items.Add(new CheckItem("migrations", false, "Migrazione dello schema non riuscita", dbDetail, + $"Npgsql: {ex.Message}", "Il database non è stato toccato oltre la migrazione fallita: annota l'errore e segnalalo.")); + await db.DisposeAsync().ConfigureAwait(false); + return (report, null); + } + + return (report, db); + } + + /// + /// Si collega al database; se non esiste e l'utente ha il permesso lo crea (il container + /// di Alberto ha POSTGRES_DB=autobidder, quindi di solito c'è già). + /// + private static async Task EnsureDatabaseAsync(DbConfig cfg, CancellationToken ct) + { + try + { + await using var conn = new NpgsqlConnection(cfg.Builder().ConnectionString); + await conn.OpenAsync(ct).ConfigureAwait(false); + } + catch (PostgresException ex) when (ex.SqlState == "3D000") + { + await using var admin = new NpgsqlConnection(cfg.Builder("postgres").ConnectionString); + await admin.OpenAsync(ct).ConfigureAwait(false); + var safeName = cfg.Database.Replace("\"", "\"\"", StringComparison.Ordinal); + await using var create = new NpgsqlCommand($"CREATE DATABASE \"{safeName}\"", admin); + await create.ExecuteNonQueryAsync(ct).ConfigureAwait(false); + } + } + + /// L'errore di Npgsql con una frase che dice cosa controllare. + public static string Explain(Exception ex, EnvConfig env) + { + var where = $"{env.DbHost}:{env.DbPort}"; + return ex switch + { + PostgresException { SqlState: "28P01" } => $"Npgsql: password sbagliata per l'utente {env.DbUser}", + PostgresException { SqlState: "28000" } => $"Npgsql: l'utente {env.DbUser} non può collegarsi ({ex.Message})", + PostgresException { SqlState: "3D000" } => $"Npgsql: il database {env.DbName} non esiste e l'utente non può crearlo", + PostgresException { SqlState: "42501" } => $"Npgsql: permesso negato ({ex.Message})", + _ when HasSocketError(ex, SocketError.ConnectionRefused) => $"Npgsql: connection refused ({where}) - il container PostgreSQL è spento o la porta è diversa", + _ when HasSocketError(ex, SocketError.HostNotFound) || HasSocketError(ex, SocketError.NoData) => $"Npgsql: indirizzo {env.DbHost} sconosciuto", + _ when ex is TimeoutException || ex.InnerException is TimeoutException || ex.Message.Contains("Timeout", StringComparison.OrdinalIgnoreCase) + => $"Npgsql: nessuna risposta da {where} entro 5 secondi - indirizzo sbagliato o rete non raggiungibile", + _ => $"Npgsql: {ex.Message}" + }; + } + + private static bool HasSocketError(Exception? ex, SocketError code) + { + for (var e = ex; e != null; e = e.InnerException) + if (e is SocketException s && s.SocketErrorCode == code) return true; + return false; + } +} diff --git a/Mimante/src/BidooBidBot/Data/Db.cs b/Mimante/src/BidooBidBot/Data/Db.cs new file mode 100644 index 0000000..7fcb2af --- /dev/null +++ b/Mimante/src/BidooBidBot/Data/Db.cs @@ -0,0 +1,200 @@ +using System.Data.Common; +using Npgsql; +using NpgsqlTypes; + +namespace BidooBidBot.Data; + +/// Parametri di connessione, dalle variabili d'ambiente (specifica §10.1). +public sealed record DbConfig(string Host, int Port, string User, string Password, string Database) +{ + /// Descrizione senza segreti, per la schermata d'errore e il registro. + public string Describe() => $"{Host}:{Port} utente {User} database {Database}"; + + public NpgsqlConnectionStringBuilder Builder(string? database = null, int commandTimeoutSeconds = 30) => new() + { + Host = Host, + Port = Port, + Username = User, + Password = Password, + Database = database ?? Database, + Timeout = 5, + CommandTimeout = commandTimeoutSeconds, + Pooling = true, + MaxPoolSize = 20, + ApplicationName = "bidoo-bidbot", + IncludeErrorDetail = false + }; +} + +/// Un parametro da passare come jsonb: il testo è già JSON. +public readonly record struct Jsonb(string? Json); + +/// +/// Accesso a PostgreSQL con SQL scritto a mano e parametri posizionali ($1, $2…). +/// +/// Due sorgenti di connessioni: una per le scritture (la usa solo +/// , più le migrazioni e la manutenzione) e una per le letture +/// dell'interfaccia, con un tempo massimo breve, così una pagina lenta non trattiene le +/// connessioni che servono alla coda. +/// +public sealed class Db : IAsyncDisposable +{ + public DbConfig Config { get; } + public NpgsqlDataSource Writer { get; } + public NpgsqlDataSource Reader { get; } + + public Db(DbConfig config) + { + Config = config; + Writer = NpgsqlDataSource.Create(config.Builder(commandTimeoutSeconds: 120)); + Reader = NpgsqlDataSource.Create(config.Builder(commandTimeoutSeconds: 15)); + } + + public static NpgsqlCommand Command(NpgsqlConnection connection, string sql, IReadOnlyList args) + { + var cmd = new NpgsqlCommand(sql, connection); + foreach (var arg in args) cmd.Parameters.Add(Parameter(arg)); + return cmd; + } + + public static NpgsqlBatchCommand BatchCommand(string sql, IReadOnlyList args) + { + var cmd = new NpgsqlBatchCommand(sql); + foreach (var arg in args) cmd.Parameters.Add(Parameter(arg)); + return cmd; + } + + /// + /// Un parametro posizionale. Null diventa NULL senza tipo (PostgreSQL lo ricava dal + /// contesto); le date devono essere UTC, diventa jsonb. + /// + public static NpgsqlParameter Parameter(object? value) => value switch + { + null => new NpgsqlParameter { Value = DBNull.Value }, + Jsonb j => new NpgsqlParameter { NpgsqlDbType = NpgsqlDbType.Jsonb, Value = (object?)j.Json ?? DBNull.Value }, + DateTime d => new NpgsqlParameter { NpgsqlDbType = NpgsqlDbType.TimestampTz, Value = d.Kind == DateTimeKind.Utc ? d : d.ToUniversalTime() }, + DateTimeOffset o => new NpgsqlParameter { NpgsqlDbType = NpgsqlDbType.TimestampTz, Value = o.UtcDateTime }, + _ => new NpgsqlParameter { Value = value } + }; + + /// Righe di una lettura, già trasformate. Usa la sorgente delle letture. + public async Task> QueryAsync(string sql, Func map, params object?[] args) + { + await using var conn = await Reader.OpenConnectionAsync().ConfigureAwait(false); + await using var cmd = Command(conn, sql, args); + await using var reader = await cmd.ExecuteReaderAsync().ConfigureAwait(false); + var list = new List(); + while (await reader.ReadAsync().ConfigureAwait(false)) list.Add(map(reader)); + return list; + } + + public async Task QueryOneAsync(string sql, Func map, params object?[] args) where T : class + { + var rows = await QueryAsync(sql, map, args).ConfigureAwait(false); + return rows.Count > 0 ? rows[0] : null; + } + + /// Il primo valore della prima riga, convertito; default se non c'è o è NULL. + public async Task ScalarAsync(string sql, params object?[] args) + { + await using var conn = await Reader.OpenConnectionAsync().ConfigureAwait(false); + await using var cmd = Command(conn, sql, args); + var value = await cmd.ExecuteScalarAsync().ConfigureAwait(false); + return value is null or DBNull ? default : (T)Convert.ChangeType(value, Nullable.GetUnderlyingType(typeof(T)) ?? typeof(T), System.Globalization.CultureInfo.InvariantCulture); + } + + /// + /// Una scrittura diretta, fuori dalla coda. Solo per migrazioni, manutenzione e + /// operazioni lunghe chieste dall'utente: il motore scrive sempre attraverso la coda. + /// + public async Task ExecuteAsync(string sql, params object?[] args) + { + await using var conn = await Writer.OpenConnectionAsync().ConfigureAwait(false); + await using var cmd = Command(conn, sql, args); + return await cmd.ExecuteNonQueryAsync().ConfigureAwait(false); + } + + public async ValueTask DisposeAsync() + { + await Writer.DisposeAsync().ConfigureAwait(false); + await Reader.DisposeAsync().ConfigureAwait(false); + } +} + +/// Letture comode e tolleranti ai NULL dalle righe di . +public static class RowExtensions +{ + public static string Str(this DbDataReader r, string name) + { + var i = r.GetOrdinal(name); + return r.IsDBNull(i) ? "" : Convert.ToString(r.GetValue(i), System.Globalization.CultureInfo.InvariantCulture) ?? ""; + } + + public static string? StrOrNull(this DbDataReader r, string name) + { + var i = r.GetOrdinal(name); + return r.IsDBNull(i) ? null : Convert.ToString(r.GetValue(i), System.Globalization.CultureInfo.InvariantCulture); + } + + public static double Dbl(this DbDataReader r, string name) => r.DblOrNull(name) ?? 0; + + public static double? DblOrNull(this DbDataReader r, string name) + { + var i = r.GetOrdinal(name); + return r.IsDBNull(i) ? null : Convert.ToDouble(r.GetValue(i), System.Globalization.CultureInfo.InvariantCulture); + } + + public static int Int(this DbDataReader r, string name) => r.IntOrNull(name) ?? 0; + + public static int? IntOrNull(this DbDataReader r, string name) + { + var i = r.GetOrdinal(name); + return r.IsDBNull(i) ? null : Convert.ToInt32(r.GetValue(i), System.Globalization.CultureInfo.InvariantCulture); + } + + public static long Long(this DbDataReader r, string name) => r.LongOrNull(name) ?? 0; + + public static long? LongOrNull(this DbDataReader r, string name) + { + var i = r.GetOrdinal(name); + return r.IsDBNull(i) ? null : Convert.ToInt64(r.GetValue(i), System.Globalization.CultureInfo.InvariantCulture); + } + + public static bool Bool(this DbDataReader r, string name) + { + var i = r.GetOrdinal(name); + return !r.IsDBNull(i) && Convert.ToBoolean(r.GetValue(i), System.Globalization.CultureInfo.InvariantCulture); + } + + public static bool? BoolOrNull(this DbDataReader r, string name) + { + var i = r.GetOrdinal(name); + return r.IsDBNull(i) ? null : Convert.ToBoolean(r.GetValue(i), System.Globalization.CultureInfo.InvariantCulture); + } + + /// Un timestamptz come istante UTC; null se NULL. + public static DateTime? Date(this DbDataReader r, string name) + { + var i = r.GetOrdinal(name); + if (r.IsDBNull(i)) return null; + var v = r.GetValue(i); + return v switch + { + DateTime d => d.Kind == DateTimeKind.Utc ? d : DateTime.SpecifyKind(d, DateTimeKind.Utc), + DateTimeOffset o => o.UtcDateTime, + _ => null + }; + } + + /// Tutte le colonne della riga in un dizionario: per le pagine che mostrano righe intere. + public static Dictionary ToDictionary(this DbDataReader r) + { + var d = new Dictionary(r.FieldCount, StringComparer.Ordinal); + for (var i = 0; i < r.FieldCount; i++) + { + var v = r.IsDBNull(i) ? null : r.GetValue(i); + d[r.GetName(i)] = v is decimal m ? (double)m : v; + } + return d; + } +} diff --git a/Mimante/src/BidooBidBot/Data/DocumentStore.cs b/Mimante/src/BidooBidBot/Data/DocumentStore.cs new file mode 100644 index 0000000..44924dd --- /dev/null +++ b/Mimante/src/BidooBidBot/Data/DocumentStore.cs @@ -0,0 +1,85 @@ +using System.Collections.Concurrent; + +namespace BidooBidBot.Data; + +/// +/// Documenti chiave → JSON: i modelli appresi (ml/*), le aste in elenco +/// (monitor/auctions), l'HALT (risk/halt). Letture sincrone da una copia in +/// memoria, scritture accodate: nessuno dei chiamanti (motore, apprendimento) aspetta il +/// database. +/// +public interface IDocumentStore +{ + string? Get(string key); + void Set(string key, string json); + void Delete(string key); + void DeletePrefix(string prefix); + IReadOnlyList Keys(string prefix); +} + +/// Documenti su PostgreSQL (tabella documents), caricati tutti all'avvio. +public sealed class DocumentStore : IDocumentStore +{ + private readonly ConcurrentDictionary _cache = new(StringComparer.Ordinal); + private readonly WriteQueue _queue; + + public DocumentStore(WriteQueue queue) => _queue = queue; + + /// Legge tutti i documenti in memoria. Sono pochi: i modelli pesano qualche centinaio di KB. + public async Task LoadAsync(Db db) + { + var rows = await db.QueryAsync("SELECT key, value::text AS value FROM documents", + r => (Key: r.Str("key"), Value: r.Str("value"))).ConfigureAwait(false); + _cache.Clear(); + foreach (var (key, value) in rows) _cache[key] = value; + } + + public string? Get(string key) => _cache.TryGetValue(key, out var v) ? v : null; + + public void Set(string key, string json) + { + _cache[key] = json; + _queue.Enqueue( + "INSERT INTO documents(key, value, updated_at) VALUES($1, $2, now()) " + + "ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at", + key, new Jsonb(json)); + } + + public void Delete(string key) + { + _cache.TryRemove(key, out _); + _queue.Enqueue("DELETE FROM documents WHERE key = $1", key); + } + + public void DeletePrefix(string prefix) + { + foreach (var k in _cache.Keys.Where(k => k.StartsWith(prefix, StringComparison.Ordinal)).ToList()) + _cache.TryRemove(k, out _); + var pattern = prefix.Replace("\\", "\\\\", StringComparison.Ordinal) + .Replace("%", "\\%", StringComparison.Ordinal) + .Replace("_", "\\_", StringComparison.Ordinal) + "%"; + _queue.Enqueue("DELETE FROM documents WHERE key LIKE $1", pattern); + } + + public IReadOnlyList Keys(string prefix) => + _cache.Keys.Where(k => k.StartsWith(prefix, StringComparison.Ordinal)).OrderBy(k => k, StringComparer.Ordinal).ToList(); +} + +/// Documenti in memoria soltanto: test e simulatore. +public sealed class MemoryDocumentStore : IDocumentStore +{ + private readonly ConcurrentDictionary _docs = new(StringComparer.Ordinal); + + public string? Get(string key) => _docs.TryGetValue(key, out var v) ? v : null; + public void Set(string key, string json) => _docs[key] = json; + public void Delete(string key) => _docs.TryRemove(key, out _); + + public void DeletePrefix(string prefix) + { + foreach (var k in _docs.Keys.Where(k => k.StartsWith(prefix, StringComparison.Ordinal)).ToList()) + _docs.TryRemove(k, out _); + } + + public IReadOnlyList Keys(string prefix) => + _docs.Keys.Where(k => k.StartsWith(prefix, StringComparison.Ordinal)).OrderBy(k => k, StringComparer.Ordinal).ToList(); +} diff --git a/Mimante/src/BidooBidBot/Data/Migrations.cs b/Mimante/src/BidooBidBot/Data/Migrations.cs new file mode 100644 index 0000000..1130dc8 --- /dev/null +++ b/Mimante/src/BidooBidBot/Data/Migrations.cs @@ -0,0 +1,147 @@ +using System.Globalization; +using System.Reflection; +using System.Text.RegularExpressions; +using Npgsql; + +namespace BidooBidBot.Data; + +/// +/// Le migrazioni SQL incorporate nel binario (Data/Migrations/NNNN_nome.sql), +/// applicate in ordine, una transazione per file, registrate in schema_migrations. +/// Sempre additive. Una migrazione fallita ferma l'avvio e porta alla schermata d'errore. +/// +public static partial class Migrations +{ + public sealed record Script(int Version, string Name, string Sql); + + /// Gli script incorporati, in ordine di versione. + public static IReadOnlyList + + """; + + /// La pagina di accesso: un solo campo, la versione, l'errore in chiaro. + public static string Login(string version, string? error, int waitSeconds) + { + var sb = new StringBuilder(); + sb.Append(Head("Bidoo BidBot - accesso")); + sb.Append($$""" + +
+

Bidoo BidBot{{E(version)}}

+

Inserisci la password dell'interfaccia (quella impostata in UI_PASSWORD nel container).

+
+ 0 ? "disabled" : "")}}> + +
+ """); + + if (!string.IsNullOrEmpty(error)) + sb.Append($""""""); + + sb.Append(""" +

Password sbagliata: dopo 5 tentativi l'attesa cresce. La sessione dura 30 giorni su questo browser.

+
+ """); + + if (waitSeconds > 0) + sb.Append($""); + + sb.Append(""); + return sb.ToString(); + } + + /// + /// La schermata d'errore di configurazione: cosa manca o non risponde, con i valori in + /// uso (mai le password), l'errore testuale, il prossimo tentativo, «Riprova adesso» e + /// le istruzioni per Unraid. Nient'altro dell'interfaccia è raggiungibile. + /// + public static string ConfigError(string version, StartupReport report, int nextRetrySeconds) + { + var sb = new StringBuilder(); + sb.Append(Head("Bidoo BidBot - errore di configurazione")); + sb.Append($$""" + +
+

Bidoo BidBot non può partire + {{E(version)}} · tentativo {{report.Attempt}} · prossimo fra {{nextRetrySeconds}} s

+ """); + + foreach (var item in report.Items) + { + var cls = item.Ok ? "err-item ok" : "err-item"; + var mark = item.Ok ? "✓" : "✕"; + sb.Append($"""
"""); + sb.Append($"{E(item.Title)}"); + if (!string.IsNullOrEmpty(item.Detail)) sb.Append($" {FormatDetail(item.Detail)}"); + if (!item.Ok && !string.IsNullOrEmpty(item.Error)) sb.Append($"
{E(item.Error)}
"); + sb.Append("
"); + } + + var hint = report.FirstProblem?.Hint + ?? "Su Unraid: Docker ▸ postgresql18 ▸ avvia; poi controlla porta e password nel template di bidoo-bidbot."; + + sb.Append($$""" +

Finché l'errore resta, il motore è fermo: nessuna asta seguita, nessuna puntata. Il bot riprova da solo ogni 30 secondi.

+
+
+ {{E(hint)}} +
+
+ + + """); + return sb.ToString(); + } + + /// Tra le verifiche riuscite e il motore pronto passa qualche secondo. + public static string Starting(string version, string step) => + Head("Bidoo BidBot - avvio") + $$""" + +
+

Bidoo BidBot{{E(version)}}

+

Avvio in corso: {{E(step)}}

+

La pagina si ricarica da sola appena il bot è pronto.

+
+ + + """; + + /// I valori «chiave valore · chiave valore» con i valori in codice, come nel mockup. + private static string FormatDetail(string detail) => E(detail); +} diff --git a/Mimante/src/BidooBidBot/Web/UiAuth.cs b/Mimante/src/BidooBidBot/Web/UiAuth.cs new file mode 100644 index 0000000..90228ad --- /dev/null +++ b/Mimante/src/BidooBidBot/Web/UiAuth.cs @@ -0,0 +1,141 @@ +using System.Collections.Concurrent; +using System.Security.Cryptography; +using System.Text; +using BidooBidBot.Config; + +namespace BidooBidBot.Web; + +/// +/// Accesso all'interfaccia con la password di UI_PASSWORD (specifica §11). +/// +/// +/// La password si confronta a tempo costante con quella dell'ambiente: niente hash +/// su disco, la fonte è la variabile. +/// Il cookie di sessione è firmato (HMAC-SHA256) con una chiave generata al primo +/// avvio in /config/sessione/interfaccia.key, mescolata con la password: cambiare +/// UI_PASSWORD fa uscire tutti i browser. +/// Dura 30 giorni e si rinnova a ogni uso (al massimo una volta al giorno). +/// Dopo 5 tentativi sbagliati dallo stesso indirizzo l'attesa cresce: 2, 4, 8… s. +/// +/// +public sealed class UiAuth +{ + public const string CookieName = "bidbot_sessione"; + public static readonly TimeSpan Lifetime = TimeSpan.FromDays(30); + private static readonly TimeSpan RenewAfter = TimeSpan.FromDays(1); + private const int FreeAttempts = 5; + + private readonly byte[] _passwordHash; + private readonly byte[] _macKey; + private readonly ConcurrentDictionary _attempts = new(StringComparer.Ordinal); + + public UiAuth(string password, byte[] fileKey) + { + _passwordHash = SHA256.HashData(Encoding.UTF8.GetBytes(password)); + _macKey = HMACSHA256.HashData(fileKey, Encoding.UTF8.GetBytes("interfaccia:" + password)); + } + + /// La chiave dei cookie: letta dal file, o generata e scritta con permessi 0600. + public static byte[] LoadOrCreateKey(string path) + { + try + { + if (File.Exists(path)) + { + var existing = File.ReadAllBytes(path); + if (existing.Length >= 32) return existing; + } + } + catch { /* chiave illeggibile: se ne fa una nuova, i browser dovranno rientrare */ } + + var key = RandomNumberGenerator.GetBytes(32); + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + File.WriteAllBytes(path, key); + ConfigPaths.RestrictToOwner(path); + return key; + } + + /// Confronto a tempo costante: gli hash hanno la stessa lunghezza qualunque sia la password tentata. + public bool CheckPassword(string? attempt) + { + var hash = SHA256.HashData(Encoding.UTF8.GetBytes(attempt ?? "")); + return CryptographicOperations.FixedTimeEquals(hash, _passwordHash); + } + + /// Un cookie nuovo: istante di emissione, scadenza, casuale, firma. + public string IssueToken(DateTimeOffset now) + { + var payload = $"{now.ToUnixTimeSeconds()}.{now.Add(Lifetime).ToUnixTimeSeconds()}.{Convert.ToHexString(RandomNumberGenerator.GetBytes(8))}"; + return Base64Url(Encoding.ASCII.GetBytes(payload)) + "." + Base64Url(Sign(payload)); + } + + public readonly record struct TokenCheck(bool Valid, bool ShouldRenew); + + public TokenCheck Validate(string? token, DateTimeOffset now) + { + if (string.IsNullOrEmpty(token)) return default; + + var dot = token.LastIndexOf('.'); + if (dot <= 0) return default; + + byte[] payloadBytes, signature; + try + { + payloadBytes = FromBase64Url(token[..dot]); + signature = FromBase64Url(token[(dot + 1)..]); + } + catch (FormatException) { return default; } + + var payload = Encoding.ASCII.GetString(payloadBytes); + if (!CryptographicOperations.FixedTimeEquals(Sign(payload), signature)) return default; + + var parts = payload.Split('.'); + if (parts.Length != 3 || !long.TryParse(parts[0], out var issued) || !long.TryParse(parts[1], out var expires)) + return default; + + var nowSec = now.ToUnixTimeSeconds(); + if (nowSec >= expires) return default; + + return new TokenCheck(true, nowSec - issued > (long)RenewAfter.TotalSeconds); + } + + /// Quanto deve ancora aspettare questo indirizzo prima di riprovare. Zero = può. + public TimeSpan LockedFor(string client, DateTimeOffset now) => + _attempts.TryGetValue(client, out var a) && a.LockedUntil > now ? a.LockedUntil - now : TimeSpan.Zero; + + /// Un tentativo sbagliato. Restituisce l'attesa imposta da adesso (zero nei primi cinque). + public TimeSpan RecordFailure(string client, DateTimeOffset now) + { + var entry = _attempts.AddOrUpdate(client, + _ => (1, DateTimeOffset.MinValue), + (_, old) => (old.Failures + 1, old.LockedUntil)); + + if (entry.Failures < FreeAttempts) return TimeSpan.Zero; + + var exponent = Math.Min(entry.Failures - FreeAttempts, 10); + var wait = TimeSpan.FromSeconds(2 << exponent); // 2, 4, 8, ... fino a ~34 minuti + _attempts[client] = (entry.Failures, now.Add(wait)); + return wait; + } + + public int Failures(string client) => _attempts.TryGetValue(client, out var a) ? a.Failures : 0; + + public void RecordSuccess(string client) => _attempts.TryRemove(client, out _); + + private byte[] Sign(string payload) => HMACSHA256.HashData(_macKey, Encoding.ASCII.GetBytes(payload)); + + private static string Base64Url(byte[] data) => + Convert.ToBase64String(data).TrimEnd('=').Replace('+', '-').Replace('/', '_'); + + private static byte[] FromBase64Url(string text) + { + var s = text.Replace('-', '+').Replace('_', '/'); + switch (s.Length % 4) + { + case 2: s += "=="; break; + case 3: s += "="; break; + case 1: throw new FormatException(); + } + return Convert.FromBase64String(s); + } +} diff --git a/Mimante/src/BidooBidBot/Web/WebServer.cs b/Mimante/src/BidooBidBot/Web/WebServer.cs new file mode 100644 index 0000000..48e3e0c --- /dev/null +++ b/Mimante/src/BidooBidBot/Web/WebServer.cs @@ -0,0 +1,232 @@ +using System.Net; +using System.Text.Json; +using BidooBidBot.Host; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.FileProviders; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; + +namespace BidooBidBot.Web; + +/// +/// Kestrel sulla porta dell'interfaccia (8080). Parte prima di tutto il resto, perché deve +/// poter mostrare la schermata d'errore quando il bot non può partire; in quello stato +/// risponde solo con quella su ogni percorso, e /salute dà 503. +/// +/// A bot in funzione: /accesso e i fogli di stile sono pubblici, tutto il resto +/// (pagina, moduli JS, WebSocket, esportazioni) chiede il cookie dell'interfaccia. +/// +public static class WebServer +{ + public static WebApplication Build(BotHost host) + { + var builder = WebApplication.CreateSlimBuilder(new WebApplicationOptions + { + ContentRootPath = AppContext.BaseDirectory, + WebRootPath = Path.Combine(AppContext.BaseDirectory, "wwwroot"), + Args = Array.Empty() + }); + + builder.Logging.ClearProviders(); + builder.WebHost.ConfigureKestrel(o => + { + o.ListenAnyIP(host.Env.HttpPort); + o.AddServerHeader = false; + o.Limits.MaxRequestBodySize = 2 * 1024 * 1024; + }); + builder.Services.AddRouting(); + + var app = builder.Build(); + app.UseWebSockets(new WebSocketOptions { KeepAliveInterval = TimeSpan.FromSeconds(20) }); + + app.Use((ctx, next) => Gate(host, ctx, next)); + + var files = new PhysicalFileProvider(app.Environment.WebRootPath); + app.UseDefaultFiles(new DefaultFilesOptions { FileProvider = files }); + app.UseStaticFiles(new StaticFileOptions + { + FileProvider = files, + OnPrepareResponse = c => + { + // L'interfaccia cambia con la versione: niente cache lunga su pagina e moduli. + c.Context.Response.Headers.CacheControl = "no-cache"; + } + }); + + return app; + } + + /// + /// Il cancello unico: stato del processo, poi autenticazione, poi i percorsi del server. + /// + private static async Task Gate(BotHost host, HttpContext ctx, Func next) + { + var path = ctx.Request.Path.Value ?? "/"; + var method = ctx.Request.Method; + + if (path == "/salute") + { + await Health.WriteAsync(host, ctx).ConfigureAwait(false); + return; + } + + // Fogli di stile e icona servono anche alle pagine d'errore e d'accesso. + if (IsPublicAsset(path)) + { + await next().ConfigureAwait(false); + return; + } + + if (host.State != HostState.Running || host.Bot == null) + { + if (path == "/riprova" && HttpMethods.IsPost(method)) + { + host.RequestRetry(); + ctx.Response.Redirect("/"); + return; + } + + ctx.Response.StatusCode = 503; + ctx.Response.ContentType = "text/html; charset=utf-8"; + ctx.Response.Headers.CacheControl = "no-store"; + + var html = host.State == HostState.ConfigError && host.LastReport != null + ? Pages.ConfigError(AppInfo.Version, host.LastReport, + Math.Max(0, (int)Math.Ceiling((host.NextRetryAt - DateTimeOffset.UtcNow).TotalSeconds))) + : Pages.Starting(AppInfo.Version, host.StartingStep); + await ctx.Response.WriteAsync(html).ConfigureAwait(false); + return; + } + + var auth = host.Auth!; + var client = ClientKey(ctx); + + if (path == "/accesso") + { + if (HttpMethods.IsPost(method)) await LoginAsync(host, auth, ctx, client).ConfigureAwait(false); + else await LoginPageAsync(auth, ctx, client, null).ConfigureAwait(false); + return; + } + + var check = auth.Validate(ctx.Request.Cookies[UiAuth.CookieName], DateTimeOffset.UtcNow); + if (!check.Valid) + { + if (path.StartsWith("/ws", StringComparison.Ordinal) || path.StartsWith("/api", StringComparison.Ordinal)) + { + ctx.Response.StatusCode = 401; + return; + } + ctx.Response.Redirect("/accesso"); + return; + } + + if (check.ShouldRenew) SetCookie(ctx, auth.IssueToken(DateTimeOffset.UtcNow)); + + if (path == "/esci") + { + ctx.Response.Cookies.Delete(UiAuth.CookieName); + host.Log.Info("ACCESSO", $"Uscita dall'interfaccia da {client}"); + ctx.Response.Redirect("/accesso"); + return; + } + + if (path == "/ws") + { + if (!ctx.WebSockets.IsWebSocketRequest) + { + ctx.Response.StatusCode = 400; + return; + } + await host.Bot.Hub.AcceptAsync(ctx).ConfigureAwait(false); + return; + } + + if (path.StartsWith("/esportazioni/", StringComparison.Ordinal)) + { + await Downloads.ServeExportAsync(host, ctx, path["/esportazioni/".Length..]).ConfigureAwait(false); + return; + } + + if (path.StartsWith("/registri/", StringComparison.Ordinal)) + { + await Downloads.ServeLogAsync(host, ctx, path["/registri/".Length..]).ConfigureAwait(false); + return; + } + + await next().ConfigureAwait(false); + } + + private static bool IsPublicAsset(string path) => + path.StartsWith("/css/", StringComparison.Ordinal) || + path.StartsWith("/img/", StringComparison.Ordinal) || + path == "/favicon.ico"; + + private static async Task LoginPageAsync(UiAuth auth, HttpContext ctx, string client, string? error) + { + var wait = auth.LockedFor(client, DateTimeOffset.UtcNow); + if (wait > TimeSpan.Zero && error == null) + error = $"Troppi tentativi sbagliati: riprova fra {Math.Ceiling(wait.TotalSeconds):N0} secondi."; + + ctx.Response.ContentType = "text/html; charset=utf-8"; + ctx.Response.Headers.CacheControl = "no-store"; + await ctx.Response.WriteAsync(Pages.Login(AppInfo.Version, error, (int)Math.Ceiling(wait.TotalSeconds))).ConfigureAwait(false); + } + + private static async Task LoginAsync(BotHost host, UiAuth auth, HttpContext ctx, string client) + { + var now = DateTimeOffset.UtcNow; + var wait = auth.LockedFor(client, now); + if (wait > TimeSpan.Zero) + { + await LoginPageAsync(auth, ctx, client, null).ConfigureAwait(false); + return; + } + + string? password = null; + if (ctx.Request.HasFormContentType) + { + var form = await ctx.Request.ReadFormAsync().ConfigureAwait(false); + password = form["password"].ToString(); + } + + if (auth.CheckPassword(password)) + { + auth.RecordSuccess(client); + SetCookie(ctx, auth.IssueToken(now)); + host.Log.Info("ACCESSO", $"Accesso all'interfaccia da {client}"); + ctx.Response.Redirect("/"); + return; + } + + var lockFor = auth.RecordFailure(client, now); + var failures = auth.Failures(client); + host.Log.Warn("ACCESSO", $"Password dell'interfaccia sbagliata da {client} ({failures} di fila)" + + (lockFor > TimeSpan.Zero ? $", attesa {lockFor.TotalSeconds:N0} s" : "")); + + var error = lockFor > TimeSpan.Zero + ? $"Password sbagliata. Troppi tentativi: riprova fra {lockFor.TotalSeconds:N0} secondi." + : "Password sbagliata."; + ctx.Response.StatusCode = 401; + await LoginPageAsync(auth, ctx, client, error).ConfigureAwait(false); + } + + private static void SetCookie(HttpContext ctx, string token) => + ctx.Response.Cookies.Append(UiAuth.CookieName, token, new CookieOptions + { + HttpOnly = true, + SameSite = SameSiteMode.Strict, + Secure = ctx.Request.IsHttps, + MaxAge = UiAuth.Lifetime, + Path = "/" + }); + + /// + /// Chi sta chiedendo, per contare i tentativi. Solo l'indirizzo della connessione: + /// fidarsi di X-Forwarded-For permetterebbe di aggirare l'attesa cambiando l'intestazione. + /// Dietro un proxy i tentativi si contano tutti insieme, che è il lato prudente. + /// + private static string ClientKey(HttpContext ctx) => + ctx.Connection.RemoteIpAddress?.ToString() ?? "sconosciuto"; +} diff --git a/Mimante/src/BidooBidBot/Web/WebSocketHub.cs b/Mimante/src/BidooBidBot/Web/WebSocketHub.cs new file mode 100644 index 0000000..1258eec --- /dev/null +++ b/Mimante/src/BidooBidBot/Web/WebSocketHub.cs @@ -0,0 +1,13 @@ +using Microsoft.AspNetCore.Http; + +namespace BidooBidBot.Web; + +/// Segnaposto fino a M6: il protocollo WebSocket completo arriva con l'interfaccia. +public sealed class WebSocketHub +{ + public async Task AcceptAsync(HttpContext ctx) + { + using var socket = await ctx.WebSockets.AcceptWebSocketAsync().ConfigureAwait(false); + await socket.CloseAsync(System.Net.WebSockets.WebSocketCloseStatus.NormalClosure, "non ancora disponibile", CancellationToken.None).ConfigureAwait(false); + } +} diff --git a/Mimante/src/BidooBidBot/wwwroot/css/app.css b/Mimante/src/BidooBidBot/wwwroot/css/app.css new file mode 100644 index 0000000..dd59336 --- /dev/null +++ b/Mimante/src/BidooBidBot/wwwroot/css/app.css @@ -0,0 +1,360 @@ +/* + Bidoo BidBot — componenti dell'interfaccia. Solo token di tokens.css, niente colori + scritti qui. Densità compatta; layout fluido (grid/flex con 1fr, nessuna larghezza fissa + nelle colonne della griglia); le maniglie cambiano solo grid-template-columns/rows. +*/ +*, *::before, *::after { box-sizing: border-box; } + +html, body { + margin: 0; + height: 100%; + background: var(--bg); + color: var(--text); + font: var(--fs)/1.35 var(--font); + font-variant-numeric: tabular-nums; +} + +a { color: var(--accent); } +code { font-family: var(--mono); font-size: .95em; background: var(--surface-2); border: 1px solid var(--line); border-radius: 3px; padding: 0 4px; } +b, strong { font-weight: 600; } +button, input, select, textarea { font: inherit; color: inherit; } +button { cursor: pointer; } +button:disabled { cursor: not-allowed; opacity: .55; } +:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; } +[hidden] { display: none !important; } + +::-webkit-scrollbar { width: 10px; height: 10px; } +::-webkit-scrollbar-thumb { background: var(--surface-3); border-radius: 6px; border: 2px solid var(--bg); } +::-webkit-scrollbar-track { background: transparent; } + +.muted { color: var(--muted); } +.faint { color: var(--faint); } +.small { font-size: var(--fs-small); color: var(--muted); } +.help { color: var(--faint); font-size: var(--fs-small); } +.right, .num { text-align: right; } +.nowrap { white-space: nowrap; } +.ok { color: var(--ok); } +.warn { color: var(--warn); } +.bad { color: var(--bad); } +.gold, .me, .won { color: var(--gold); font-weight: 600; } +.pos { color: var(--ok); } +.neg { color: var(--bad); } +.spacer { flex: 1; } + +/* ── bottoni e campi ─────────────────────────────────────────────────── */ +.btn { + display: inline-flex; align-items: center; gap: 6px; + padding: 6px 11px; border-radius: var(--r); + border: 1px solid var(--line); background: var(--surface-2); color: var(--text); + white-space: nowrap; line-height: 1.2; +} +.btn:hover:not(:disabled) { background: var(--surface-3); } +.btn.primary { background: var(--accent); border-color: var(--accent); color: var(--accent-ink); font-weight: 600; } +.btn.primary:hover:not(:disabled) { filter: brightness(1.08); background: var(--accent); } +.btn.danger { background: var(--bad); border-color: var(--bad); color: #fff; font-weight: 600; } +.btn.ghost { background: transparent; } +.btn.wide { width: 100%; justify-content: center; padding: 9px; } +.btn .ic { font-size: 12px; } + +input.txt, select.txt, textarea.txt, .field input, .field select { + background: var(--surface-2); border: 1px solid var(--line); color: var(--text); + border-radius: var(--r); padding: 5px 8px; min-width: 0; +} +input.txt:focus, select.txt:focus, .field input:focus, .field select:focus { border-color: var(--accent); outline: none; } +input[type="number"] { -moz-appearance: textfield; } +input[type="number"]::-webkit-inner-spin-button { opacity: .4; } + +/* interruttore: checkbox con aspetto a levetta */ +.switch { position: relative; display: inline-block; width: 34px; height: 18px; flex: none; } +.switch input { position: absolute; opacity: 0; width: 100%; height: 100%; margin: 0; cursor: pointer; z-index: 1; } +.switch span { position: absolute; inset: 0; border-radius: 9px; background: var(--line); transition: background .15s; } +.switch span::after { content: ""; position: absolute; left: 2px; top: 2px; width: 14px; height: 14px; border-radius: 50%; background: #fff; transition: transform .15s; } +.switch input:checked + span { background: var(--accent); } +.switch input:checked + span::after { transform: translateX(16px); } +.switch input:focus-visible + span { outline: 2px solid var(--accent); outline-offset: 1px; } + +.chip { + display: inline-flex; align-items: center; gap: 5px; padding: 3px 8px; min-width: 0; + border-radius: 999px; background: var(--surface-2); border: 1px solid var(--line); + color: var(--muted); white-space: nowrap; font-size: var(--fs-small); +} +.chip b { color: var(--text); font-weight: 600; } +.chip small { color: var(--faint); font-size: var(--fs-tiny); } +.chip.live { border-color: var(--bad); color: var(--bad); background: var(--bad-soft); } +.chip.live b { color: var(--bad); } +.chip.shadow { border-color: var(--accent); color: var(--accent); } +.chip.shadow b { color: var(--accent); } +.chip.sim { border-color: var(--warn); color: var(--warn); } +.chip.clickable { cursor: pointer; } +.dot { width: 9px; height: 9px; border-radius: 50%; background: var(--ok); display: inline-block; flex: none; } +.dot.warn { background: var(--warn); } +.dot.bad { background: var(--bad); } +.dot.off { background: var(--faint); } +.dot.accent { background: var(--accent); } + +.badge { display: inline-block; padding: 2px 7px; border-radius: 4px; font-size: var(--fs-tiny); font-weight: 600; letter-spacing: .1px; white-space: nowrap; } +.b-lead { background: var(--ok-soft); color: var(--ok); } +.b-active { background: var(--accent-soft); color: var(--accent); } +.b-watch { background: var(--muted-soft); color: var(--muted); } +.b-stop { background: var(--muted-soft); color: var(--faint); } +.b-won { background: var(--gold-soft); color: var(--gold); } +.b-lost { background: var(--bad-soft); color: var(--bad); } +.b-pause { background: var(--warn-soft); color: var(--warn); } +.b-sched { background: var(--muted-soft); color: var(--muted); } + +.pill { padding: 2px 8px; border-radius: 999px; font-size: var(--fs-tiny); font-weight: 600; white-space: nowrap; } +.pill.ok { background: var(--ok-soft); color: var(--ok); } +.pill.warn { background: var(--warn-soft); color: var(--warn); } +.pill.bad { background: var(--bad-soft); color: var(--bad); } +.pill.info { background: var(--accent-soft); color: var(--accent); } +.pill.muted { background: var(--muted-soft); color: var(--muted); } + +.banner { padding: 10px 14px; border-radius: var(--r); border: 1px solid var(--warn); background: var(--warn-soft); color: var(--warn); display: flex; gap: 12px; align-items: center; } +.banner.bad { border-color: var(--bad); background: var(--bad-soft); color: var(--bad); } +.banner.info { border-color: var(--accent); background: var(--accent-soft); color: var(--accent); } +.banner.ok { border-color: var(--ok); background: var(--ok-soft); color: var(--ok); } +.banner .btn { margin-left: auto; } + +/* ── pagine intere: accesso, errore, avvio ───────────────────────────── */ +body.fullpage { display: grid; place-items: center; min-height: 100vh; padding: 16px; } +.box { + width: min(440px, 100%); background: var(--surface); border: 1px solid var(--line); + border-radius: var(--r-lg); padding: 26px 28px; display: flex; flex-direction: column; gap: 12px; +} +.box h1 { margin: 0; font-size: 18px; font-weight: 600; display: flex; align-items: center; gap: 10px; flex-wrap: wrap; } +.box .v { color: var(--faint); font-size: var(--fs-small); font-weight: 400; margin-left: auto; } +.box .lead { margin: 0; color: var(--muted); } +.box form { display: flex; flex-direction: column; gap: 10px; } +.box input[type="password"] { width: 100%; background: var(--surface-2); border: 1px solid var(--line); border-radius: var(--r); padding: 9px 10px; } +.box .form-error { margin: 0; color: var(--bad); } +.box .help { margin: 0; } +.box.err { width: min(720px, 100%); } +.box .row { display: flex; gap: 12px; align-items: center; flex-wrap: wrap; } +.logo { width: 22px; height: 22px; border-radius: 5px; background: var(--accent); display: grid; place-items: center; color: var(--accent-ink); font-weight: 800; font-size: 12px; flex: none; } +.sq { width: 16px; height: 16px; background: var(--bad); border-radius: 2px; flex: none; } +.err-item { display: grid; grid-template-columns: 22px 1fr; gap: 10px; padding: 10px 12px; border-radius: var(--r); border: 1px solid var(--bad); background: var(--bad-soft); } +.err-item.ok { border-color: var(--ok); background: var(--ok-soft); } +.err-item .mark { color: var(--bad); font-weight: 700; } +.err-item.ok .mark { color: var(--ok); } +.err-item .detail { color: var(--muted); } +.mono { font-family: var(--mono); font-size: var(--fs-small); color: var(--muted); background: var(--bg); border: 1px solid var(--line); border-radius: 4px; padding: 8px 10px; white-space: pre-wrap; margin-top: 6px; } + +/* ── struttura dell'applicazione ─────────────────────────────────────── */ +.app { + display: grid; + grid-template-columns: var(--nav-w) minmax(0, 1fr); + grid-template-rows: var(--topbar-h) minmax(0, 1fr); + height: 100vh; overflow: hidden; +} +.app.narrow { grid-template-columns: var(--nav-w-narrow) minmax(0, 1fr); } + +.topbar { + grid-column: 1 / 3; display: flex; align-items: center; gap: 6px; padding: 0 12px; + overflow: hidden; background: var(--surface); border-bottom: 1px solid var(--line); min-width: 0; +} +.brand { display: flex; align-items: center; gap: 8px; font-weight: 600; font-size: 14px; margin-right: 6px; white-space: nowrap; } +.topbar .chips { display: flex; align-items: center; gap: 6px; min-width: 0; overflow: hidden; } +.halt-btn { flex: none; background: var(--bad); color: #fff; border: 0; border-radius: var(--r); padding: 6px 12px; font-weight: 700; letter-spacing: .2px; } +.halt-btn.on { background: transparent; color: var(--bad); border: 1px solid var(--bad); } +.icon-btn { flex: none; width: 30px; height: 30px; border-radius: var(--r); border: 1px solid var(--line); background: var(--surface-2); color: var(--muted); display: grid; place-items: center; font-size: 14px; padding: 0; } +.icon-btn:hover { color: var(--text); background: var(--surface-3); } + +.nav { background: var(--surface); border-right: 1px solid var(--line); padding: 10px 8px; display: flex; flex-direction: column; gap: 2px; min-height: 0; overflow: auto; } +.nav a { display: flex; align-items: center; gap: 10px; padding: 8px 10px; border-radius: var(--r); color: var(--muted); text-decoration: none; white-space: nowrap; } +.nav a:hover { color: var(--text); background: var(--surface-2); } +.nav a.on { background: var(--surface-3); color: var(--text); font-weight: 600; } +.nav .ic { width: 18px; text-align: center; font-size: 14px; flex: none; } +.nav .sep { flex: 1; } +.nav .collapse { color: var(--faint); font-size: var(--fs-small); padding: 8px 10px; background: none; border: 0; text-align: left; display: flex; gap: 10px; align-items: center; } +.app.narrow .nav .lbl { display: none; } +.app.narrow .nav a, .app.narrow .nav .collapse { justify-content: center; } + +.main { display: grid; grid-template-rows: minmax(0, 1fr) auto auto; min-width: 0; min-height: 0; overflow: hidden; } +.main.log-collapsed .bottom-log { display: none; } +.page-host { min-height: 0; min-width: 0; overflow: hidden; display: flex; flex-direction: column; } +.page-host > section { flex: 1; min-height: 0; display: flex; flex-direction: column; } + +.toolbar { display: flex; align-items: center; gap: 8px; padding: 10px 14px; border-bottom: 1px solid var(--line); background: var(--surface); flex-wrap: wrap; min-width: 0; } +.toolbar h1 { font-size: 15px; font-weight: 600; margin: 0 8px 0 0; white-space: nowrap; } +.toolbar .counter { color: var(--muted); white-space: nowrap; } +.toolbar .counter b { color: var(--text); } +.toolbar .counter.won b { color: var(--gold); } +.toolbar .sub { color: var(--muted); font-size: var(--fs-small); } + +/* due colonne ridimensionabili: elenco | maniglia | pannello */ +.split { display: grid; grid-template-columns: minmax(480px, 1fr) 6px var(--panel-w, 400px); flex: 1; min-height: 0; } +.split.collapsed { grid-template-columns: minmax(0, 1fr) 6px 0; } +.split.collapsed > .panel { display: none; } +.split > .content { overflow: auto; min-width: 0; min-height: 0; position: relative; } +.vsplit { cursor: col-resize; background: var(--surface); border-left: 1px solid var(--line); border-right: 1px solid var(--line); position: relative; } +.vsplit::after { content: ""; position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); width: 2px; height: 28px; background: var(--faint); border-radius: 2px; } +.vsplit button { position: absolute; top: 6px; left: -8px; width: 20px; height: 20px; padding: 0; border-radius: 50%; border: 1px solid var(--line); background: var(--surface-2); color: var(--muted); font-size: 10px; z-index: 2; } +.hsplit { height: 6px; cursor: row-resize; background: var(--surface); border-top: 1px solid var(--line); border-bottom: 1px solid var(--line); position: relative; } +.hsplit::after { content: ""; position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); width: 28px; height: 2px; background: var(--faint); border-radius: 2px; } +body.dragging, body.dragging * { user-select: none !important; cursor: inherit; } + +/* registro in basso */ +.bottom-log { background: var(--surface); padding: 6px 14px; font-size: var(--fs-small); color: var(--muted); height: var(--log-h, 96px); overflow: auto; line-height: 1.55; } +.bottom-log .ttl { color: var(--text); font-weight: 600; margin-right: 8px; cursor: pointer; } +.bottom-log .ttl:hover { text-decoration: underline; } +.bottom-log .line { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.bottom-log .line .ts { color: var(--faint); margin-right: 6px; } +.bottom-log .lv-warn { color: var(--warn); } +.bottom-log .lv-err { color: var(--bad); } +.bottom-log .lv-ok { color: var(--ok); } + +/* ── tabelle ─────────────────────────────────────────────────────────── */ +table.grid { border-collapse: separate; border-spacing: 0; width: 100%; } +table.grid th { + position: sticky; top: 0; z-index: 1; background: var(--surface); color: var(--muted); + font-weight: 600; text-align: left; padding: 8px 10px; border-bottom: 1px solid var(--line); + font-size: var(--fs-small); white-space: nowrap; user-select: none; +} +table.grid th.sortable { cursor: pointer; } +table.grid th.sorted-asc::after { content: " \25B4"; color: var(--accent); } +table.grid th.sorted-desc::after { content: " \25BE"; color: var(--accent); } +table.grid td { padding: 7px 10px; border-bottom: 1px solid var(--line); white-space: nowrap; vertical-align: middle; } +table.grid tbody tr { cursor: default; } +table.grid tbody tr:hover td { background: var(--surface-2); } +table.grid tbody tr.sel td { background: var(--surface-3); } +table.grid td.num, table.grid th.num { text-align: right; } +table.grid td.wrap { white-space: normal; } +table.grid td.ell { max-width: 0; overflow: hidden; text-overflow: ellipsis; } +table.grid .spacer-row td { padding: 0; border: 0; } +.empty { padding: 30px 14px; color: var(--muted); text-align: center; } + +.timer { display: flex; flex-direction: column; gap: 3px; min-width: 86px; } +.timer .t { font-weight: 600; } +.timer .t.warn { color: var(--warn); } +.timer .t.bad { color: var(--bad); } +.bar { height: 3px; border-radius: 2px; background: var(--line); overflow: hidden; } +.bar i { display: block; height: 100%; background: var(--ok); width: 0; } +.bar i.warn { background: var(--warn); } +.bar i.bad { background: var(--bad); } +.ping { color: var(--ok); } +.ping.warn { color: var(--warn); } +.ping.bad { color: var(--bad); } + +.acts { display: flex; gap: 4px; } +.acts button { width: 24px; height: 24px; padding: 0; border-radius: 4px; border: 1px solid var(--line); background: var(--surface-2); display: grid; place-items: center; font-size: 11px; color: var(--muted); } +.acts button:hover { color: var(--text); background: var(--surface-3); } +.acts button.on { border-color: var(--accent); color: var(--accent); } +.acts button.fire { color: var(--gold); } +.star { background: none; border: 0; padding: 0 2px; font-size: 14px; color: var(--faint); } +.star.on { color: var(--gold); } + +/* ── pannello dettagli ───────────────────────────────────────────────── */ +.panel { background: var(--surface); display: flex; flex-direction: column; min-height: 0; min-width: 0; } +.panel .head { padding: 10px 14px; border-bottom: 1px solid var(--line); } +.panel .head h2 { margin: 0; font-size: 14px; font-weight: 600; overflow-wrap: anywhere; } +.panel .head small { color: var(--muted); } +.tabs { display: flex; gap: 2px; padding: 6px 8px 0; border-bottom: 1px solid var(--line); overflow-x: auto; flex: none; } +.tabs button { padding: 7px 9px; color: var(--muted); border: 0; border-bottom: 2px solid transparent; background: none; white-space: nowrap; } +.tabs button.on { color: var(--text); border-color: var(--accent); font-weight: 600; } +.panel .body { padding: 12px 14px; overflow: auto; display: flex; flex-direction: column; gap: 12px; min-height: 0; flex: 1; } +.panel .placeholder { color: var(--muted); padding: 24px 14px; } + +.kv { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 6px 10px; font-size: 12.5px; margin: 0; } +.kv dt { color: var(--muted); margin: 0; } +.kv dd { margin: 0; text-align: right; font-weight: 600; } +.field { display: grid; grid-template-columns: minmax(0, 1fr) 130px; align-items: center; gap: 8px; } +.field label { color: var(--muted); } +.field input, .field select { text-align: right; width: 100%; } +.field.wide { grid-template-columns: minmax(0, 1fr) minmax(0, 220px); } +.card { background: var(--surface-2); border: 1px solid var(--line); border-radius: var(--r); padding: 10px 12px; } +.card h3 { margin: 0 0 6px; font-size: 12.5px; font-weight: 600; color: var(--muted); } +.verdict { padding: 8px 10px; border-radius: var(--r); border: 1px solid var(--muted); color: var(--muted); background: var(--muted-soft); } +.verdict.yes { border-color: var(--ok); color: var(--ok); background: var(--ok-soft); } +.verdict.no { border-color: var(--bad); color: var(--bad); background: var(--bad-soft); } +.verdict.explore { border-color: var(--accent); color: var(--accent); background: var(--accent-soft); } +.log { font-size: var(--fs-small); line-height: 1.5; color: var(--muted); white-space: pre-wrap; font-family: var(--font); } +.log b { color: var(--text); font-weight: 600; } +.log .cnt { color: var(--faint); } +.product { display: grid; grid-template-columns: 108px minmax(0, 1fr); gap: 12px; align-items: start; } +.product .img { width: 108px; height: 108px; border-radius: var(--r); background: var(--surface-3); display: grid; place-items: center; color: var(--faint); font-size: var(--fs-tiny); text-align: center; overflow: hidden; } +.product .img img { width: 100%; height: 100%; object-fit: contain; background: #fff; } + +/* ── pagine generiche ────────────────────────────────────────────────── */ +.page { padding: 14px; overflow: auto; display: flex; flex-direction: column; gap: 14px; min-height: 0; flex: 1; } +.grid2 { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 14px; } +.grid3 { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 14px; } +.grid4 { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 14px; } +.stat { background: var(--surface); border: 1px solid var(--line); border-radius: var(--r); padding: 12px 14px; min-width: 0; } +.stat .v { font-size: 22px; font-weight: 600; margin: 2px 0; } +.stat .l { color: var(--muted); font-size: var(--fs-small); } +.stat .s { color: var(--muted); font-size: var(--fs-small); } +.section { background: var(--surface); border: 1px solid var(--line); border-radius: var(--r); min-width: 0; display: flex; flex-direction: column; } +.section > h2 { margin: 0; padding: 10px 14px; font-size: 13.5px; font-weight: 600; border-bottom: 1px solid var(--line); display: flex; gap: 8px; align-items: center; } +.section > .in { padding: 12px 14px; display: flex; flex-direction: column; gap: 10px; } +.section > .table-wrap { overflow: auto; max-height: 420px; } +.row { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; } +.settings-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 14px; align-items: start; } +.settings-grid .field { grid-template-columns: minmax(0, 1fr) minmax(110px, 170px); } +.settings-grid .field.toggle-row { grid-template-columns: minmax(0, 1fr) auto; } + +.weights { display: flex; flex-direction: column; gap: 5px; font-size: var(--fs-small); } +.weights .w { display: grid; grid-template-columns: minmax(0, 1fr) minmax(60px, 160px) 48px; gap: 8px; align-items: center; } +.weights .w .bar { height: 6px; } +.weights .w .bar i { background: var(--accent); } +.weights .w .bar i.neg { background: var(--bad); } +.hist { height: 60px; display: flex; align-items: flex-end; gap: 2px; } +.hist i { display: block; flex: 1; background: var(--accent); opacity: .8; border-radius: 1px; min-height: 1px; } + +/* browser del bot (screencast) */ +.browser { background: var(--browser-bg); border: 1px solid var(--line); border-radius: var(--r); overflow: hidden; display: flex; flex-direction: column; min-height: 0; } +.browser .url { display: flex; gap: 8px; align-items: center; padding: 7px 10px; background: var(--surface-2); border-bottom: 1px solid var(--line); color: var(--muted); font-size: var(--fs-small); } +.browser .url span.addr { flex: 1; background: var(--bg); border: 1px solid var(--line); border-radius: 4px; padding: 4px 8px; color: var(--text); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.browser .view { position: relative; flex: 1; min-height: 300px; display: grid; place-items: center; outline: none; } +.browser .view canvas { max-width: 100%; max-height: 100%; cursor: pointer; display: block; } +.browser .view .idle { color: var(--muted); padding: 30px; text-align: center; } + +/* ── dialoghi e avvisi ───────────────────────────────────────────────── */ +.modal-back { position: fixed; inset: 0; background: rgba(0, 0, 0, .45); display: grid; place-items: center; z-index: 50; padding: 16px; } +.modal { width: min(520px, 100%); max-height: calc(100vh - 32px); overflow: auto; background: var(--surface); border: 1px solid var(--line); border-radius: var(--r-lg); box-shadow: 0 10px 40px var(--shadow); display: flex; flex-direction: column; } +.modal header { padding: 14px 16px; border-bottom: 1px solid var(--line); font-weight: 600; font-size: 14px; } +.modal .content { padding: 14px 16px; display: flex; flex-direction: column; gap: 10px; } +.modal footer { padding: 12px 16px; border-top: 1px solid var(--line); display: flex; gap: 8px; justify-content: flex-end; } +.modal .field { grid-template-columns: minmax(0, 1fr) minmax(0, 220px); } +.toasts { position: fixed; right: 16px; bottom: 16px; display: flex; flex-direction: column; gap: 8px; z-index: 60; max-width: min(420px, calc(100vw - 32px)); } +.toast { background: var(--surface); border: 1px solid var(--line); border-left: 4px solid var(--accent); border-radius: var(--r); padding: 10px 12px; box-shadow: 0 6px 24px var(--shadow); } +.toast.ok { border-left-color: var(--ok); } +.toast.warn { border-left-color: var(--warn); } +.toast.bad { border-left-color: var(--bad); } +.conn-lost { position: fixed; top: calc(var(--topbar-h) + 8px); left: 50%; transform: translateX(-50%); z-index: 40; } + +/* catalogo: categorie a sinistra */ +.catalog { display: grid; grid-template-columns: 220px minmax(0, 1fr); flex: 1; min-height: 0; } +.catalog .cats { border-right: 1px solid var(--line); overflow: auto; padding: 8px; background: var(--surface); } +.catalog .cats button { display: block; width: 100%; text-align: left; padding: 6px 10px; border: 0; background: none; border-radius: var(--r); color: var(--muted); } +.catalog .cats button.on { background: var(--surface-3); color: var(--text); font-weight: 600; } +.catalog .list { overflow: auto; min-width: 0; } +.thumb { width: 40px; height: 40px; object-fit: contain; background: #fff; border-radius: 4px; } + +/* ── finestre strette ────────────────────────────────────────────────── */ +@media (max-width: 1100px) { + .app { grid-template-columns: var(--nav-w-narrow) minmax(0, 1fr); } + .app .nav .lbl { display: none; } + .app .nav a, .app .nav .collapse { justify-content: center; } + .topbar .opt { display: none; } + .toolbar .counter { display: none; } + .split { grid-template-columns: minmax(0, 1fr) 6px 0; position: relative; } + .split > .panel { + position: absolute; top: 0; right: 0; bottom: 0; width: min(var(--panel-w, 400px), 92%); + border-left: 1px solid var(--line); box-shadow: -10px 0 30px var(--shadow); z-index: 5; + } + .split:not(.drawer-open) > .panel { display: none; } + .settings-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); } + .grid4 { grid-template-columns: repeat(2, minmax(0, 1fr)); } + .grid3 { grid-template-columns: repeat(2, minmax(0, 1fr)); } +} + +@media (max-width: 720px) { + .settings-grid, .grid2, .grid3, .grid4 { grid-template-columns: minmax(0, 1fr); } + .catalog { grid-template-columns: minmax(0, 1fr); } + .catalog .cats { display: none; } + .topbar .brand span.name { display: none; } +} + +@media (prefers-reduced-motion: reduce) { + *, *::before, *::after { transition: none !important; animation: none !important; } +} diff --git a/Mimante/src/BidooBidBot/wwwroot/css/tokens.css b/Mimante/src/BidooBidBot/wwwroot/css/tokens.css new file mode 100644 index 0000000..30178b2 --- /dev/null +++ b/Mimante/src/BidooBidBot/wwwroot/css/tokens.css @@ -0,0 +1,75 @@ +/* + Bidoo BidBot — token dell'interfaccia (unica origine dei colori). + Nati dai token semantici di docs/mockup/mock.css. Il colore ha significato: + neutro = secondario, accento = primario, verde/ambra/rosso = ok/attenzione/pericolo, + oro = asta vinta o «sono io». Tema scuro predefinito; chiaro con gli stessi nomi. +*/ +:root, +:root[data-theme="dark"] { + color-scheme: dark; + --bg: #151920; + --surface: #1c2129; + --surface-2: #232a34; + --surface-3: #2a323d; + --line: #2c3441; + --text: #e6eaf1; + --muted: #93a0b4; + --faint: #5f6b7d; + --accent: #5b9cff; + --accent-ink: #0b1d3a; + --ok: #3ecf8e; + --warn: #f2b640; + --bad: #f15b50; + --gold: #e5b94e; + --shadow: rgba(0, 0, 0, .45); + + --ok-soft: rgba(62, 207, 142, .16); + --warn-soft: rgba(242, 182, 64, .16); + --bad-soft: rgba(241, 91, 80, .14); + --accent-soft: rgba(91, 156, 255, .16); + --gold-soft: rgba(229, 185, 78, .18); + --muted-soft: rgba(147, 160, 180, .16); + + --browser-bg: #0e1116; +} + +:root[data-theme="light"] { + color-scheme: light; + --bg: #eef1f5; + --surface: #ffffff; + --surface-2: #f4f6f9; + --surface-3: #e9edf3; + --line: #d7dde6; + --text: #1b2230; + --muted: #5b6778; + --faint: #9aa5b5; + --accent: #2f6fe4; + --accent-ink: #ffffff; + --ok: #1f9d63; + --warn: #c98a10; + --bad: #d63b31; + --gold: #b8891a; + --shadow: rgba(20, 30, 50, .18); + + --ok-soft: rgba(31, 157, 99, .14); + --warn-soft: rgba(201, 138, 16, .14); + --bad-soft: rgba(214, 59, 49, .12); + --accent-soft: rgba(47, 111, 228, .12); + --gold-soft: rgba(184, 137, 26, .16); + --muted-soft: rgba(91, 103, 120, .12); + + --browser-bg: #dfe3ea; +} + +:root { + --font: "Segoe UI", system-ui, "Liberation Sans", Arial, sans-serif; + --mono: ui-monospace, "Cascadia Mono", "Liberation Mono", monospace; + --r: 6px; + --r-lg: 8px; + --fs: 13px; + --fs-small: 12px; + --fs-tiny: 11px; + --topbar-h: 46px; + --nav-w: 212px; + --nav-w-narrow: 56px; +} diff --git a/Mimante/src/BidooBidBot/wwwroot/img/icona.svg b/Mimante/src/BidooBidBot/wwwroot/img/icona.svg new file mode 100644 index 0000000..81de70a --- /dev/null +++ b/Mimante/src/BidooBidBot/wwwroot/img/icona.svg @@ -0,0 +1,4 @@ + + + B + diff --git a/Mimante/tests/BidooBidBot.Tests/BidooBidBot.Tests.csproj b/Mimante/tests/BidooBidBot.Tests/BidooBidBot.Tests.csproj new file mode 100644 index 0000000..041492c --- /dev/null +++ b/Mimante/tests/BidooBidBot.Tests/BidooBidBot.Tests.csproj @@ -0,0 +1,24 @@ + + + + false + true + BidooBidBot.Tests + + + + + + + + + + + + + + + + + + diff --git a/Mimante/tests/BidooBidBot.Tests/DatabaseTests.cs b/Mimante/tests/BidooBidBot.Tests/DatabaseTests.cs new file mode 100644 index 0000000..f8dc21a --- /dev/null +++ b/Mimante/tests/BidooBidBot.Tests/DatabaseTests.cs @@ -0,0 +1,123 @@ +using System.Text.Json; +using BidooBidBot.Data; +using BidooBidBot.Settings; +using Xunit; + +namespace BidooBidBot.Tests; + +/// Migrazioni, partizioni, coda di scrittura, documenti e impostazioni su PostgreSQL 18. +[Collection("Database")] +public class DatabaseTests +{ + private readonly DatabaseFixture _fx; + + public DatabaseTests(DatabaseFixture fx) => _fx = fx; + + [DbFact] + public async Task Le_migrazioni_sono_applicate_una_volta_sola() + { + var again = await Migrations.ApplyAsync(_fx.Db!.Writer); + Assert.Empty(again); + Assert.True(await Migrations.CurrentVersionAsync(_fx.Db) >= 1); + + // Nessuna delle tabelle che la specifica esclude. + foreach (var t in new[] { "polls", "auction_log", "network_metrics", "app_sessions", "maintenance_log" }) + Assert.False(await _fx.Db.ScalarAsync("SELECT to_regclass($1) IS NOT NULL", t)); + } + + [DbFact] + public async Task Le_partizioni_del_mese_e_del_successivo_esistono() + { + var created = await Partitions.EnsureAsync(_fx.Db!, new DateTime(2031, 12, 5)); + Assert.Equal(6, created); // dicembre 2031 e gennaio 2032, per tre tabelle + Assert.Equal(0, await Partitions.EnsureAsync(_fx.Db!, new DateTime(2031, 12, 20))); + + var list = await Partitions.ListAsync(_fx.Db!, "bids"); + Assert.Contains(list, p => p.Name == "bids_2032_01" && p.Month == new DateTime(2032, 1, 1)); + } + + [DbFact] + public async Task La_coda_scrive_a_lotti_e_svuota_allo_spegnimento() + { + await _fx.TruncateAsync(); + await using (var queue = new WriteQueue(_fx.Db!.Writer) { BatchRows = 50 }) + { + for (var i = 0; i < 230; i++) + queue.EnqueueBid("INSERT INTO bids(auction_id, username, price_after, bid_type) VALUES($1, $2, $3, $4)", + "a1", $"u{i % 7}", 0.01 * (i + 1), "Auto"); + + Assert.True(await queue.FlushAsync(TimeSpan.FromSeconds(20))); + Assert.Equal(230, queue.Written); + } + + Assert.Equal(230L, await _fx.Db.ScalarAsync("SELECT COUNT(*) FROM bids WHERE auction_id = 'a1'")); + } + + [DbFact] + public async Task Un_istruzione_sbagliata_non_blocca_le_altre() + { + await _fx.TruncateAsync(); + await using var queue = new WriteQueue(_fx.Db!.Writer); + queue.Enqueue("INSERT INTO risk_ledger(ts, kind, amount_euro) VALUES(now(), 'bid', -0.2)"); + queue.Enqueue("INSERT INTO tabella_che_non_esiste(x) VALUES(1)"); + queue.Enqueue("INSERT INTO risk_ledger(ts, kind, amount_euro) VALUES(now(), 'bid', -0.2)"); + Assert.True(await queue.FlushAsync(TimeSpan.FromSeconds(20))); + + Assert.Equal(1, queue.Failed); + Assert.Equal(2L, await _fx.Db.ScalarAsync("SELECT COUNT(*) FROM risk_ledger")); + } + + [DbFact] + public async Task I_documenti_si_rileggono_dopo_il_riavvio() + { + await _fx.TruncateAsync(); + await using (var queue = new WriteQueue(_fx.Db!.Writer)) + { + var docs = new DocumentStore(queue); + docs.Set("ml/prova", """{"a":1}"""); + docs.Set("ml/altro", """{"b":2}"""); + docs.Set("risk/halt", """{"reason":"x"}"""); + docs.DeletePrefix("ml/"); + docs.Set("ml/nuovo", """{"c":3}"""); + await queue.FlushAsync(TimeSpan.FromSeconds(20)); + } + + await using var q2 = new WriteQueue(_fx.Db.Writer); + var reloaded = new DocumentStore(q2); + await reloaded.LoadAsync(_fx.Db); + Assert.Null(reloaded.Get("ml/prova")); + Assert.NotNull(reloaded.Get("ml/nuovo")); + Assert.Contains("reason", reloaded.Get("risk/halt")); + } + + [DbFact] + public async Task Le_impostazioni_nascono_di_fabbrica_e_sopravvivono_al_riavvio() + { + await _fx.TruncateAsync(); + await using var queue = new WriteQueue(_fx.Db!.Writer); + var store = new SettingsStore(queue, null); + await store.LoadAsync(_fx.Db); + Assert.Equal(300, store.Current.LearningMinAuctions); + + var patch = JsonSerializer.Deserialize>("""{"DataCapGb": 20}""")!; + Assert.True((await store.SaveAsync(patch, null)).Ok); + + var again = new SettingsStore(queue, null); + await again.LoadAsync(_fx.Db); + Assert.Equal(20, again.Current.DataCapGb); + } +} + +public class WriteQueueCapacityTests +{ + [Fact] + public void A_coda_piena_si_scartano_prima_le_puntate_osservate() + { + var queue = new WriteQueue(null) { Capacity = 10 }; + for (var i = 0; i < 8; i++) queue.EnqueueBid("INSERT bid", i); + for (var i = 0; i < 5; i++) queue.Enqueue("INSERT altro", i); + + Assert.Equal(10, queue.Pending); + Assert.Equal(3, queue.Dropped); + } +} diff --git a/Mimante/tests/BidooBidBot.Tests/FoundationTests.cs b/Mimante/tests/BidooBidBot.Tests/FoundationTests.cs new file mode 100644 index 0000000..8cff41b --- /dev/null +++ b/Mimante/tests/BidooBidBot.Tests/FoundationTests.cs @@ -0,0 +1,301 @@ +using System.Text.Json; +using BidooBidBot.Config; +using BidooBidBot.Logging; +using BidooBidBot.Settings; +using BidooBidBot.Web; +using Xunit; + +namespace BidooBidBot.Tests; + +/// Niente simboli né emoji nei registri (portati dal legacy). +public class LogTextTests +{ + [Theory] + [InlineData("✓ Convenienza OK → tutto ok — bene… ≤ 3 × 2 €", "Convenienza OK -> tutto ok - bene... <= 3 x 2 EUR")] + [InlineData("🔥 avvio motore ⚡", "avvio motore")] + [InlineData("riga uno\r\nriga due\tfine", "riga uno riga due fine")] + [InlineData("«virgolette» e “altre”", "\"virgolette\" e \"altre\"")] + [InlineData("", "")] + public void Il_testo_esce_in_chiaro(string dentro, string fuori) + { + Assert.Equal(fuori, LogText.Clean(dentro)); + } + + [Fact] + public void Il_registro_applicativo_tiene_il_tag_e_rispetta_il_livello() + { + var log = new AppLog(null) { MinLevel = LogLevel.Info, Capacity = 50 }; + LogEntry? seen = null; + log.Entry += e => seen = e; + + log.Debug("PUNTATA", "non si vede"); + Assert.Null(seen); + + log.Info("puntata", "Buono → 4,12 €"); + Assert.NotNull(seen); + Assert.Equal("PUNTATA", seen!.Tag); + Assert.Equal("[PUNTATA] Buono -> 4,12 EUR", seen.Text); + Assert.Single(log.Snapshot()); + } + + [Fact] + public void L_anello_in_memoria_ha_un_tetto() + { + var log = new AppLog(null) { Capacity = 60 }; + for (var i = 0; i < 200; i++) log.Info("X", $"riga {i}"); + var rows = log.Snapshot(); + Assert.Equal(60, rows.Count); + Assert.Equal("riga 199", rows[^1].Message); + } + + [Fact] + public async Task Il_file_giornaliero_riceve_le_righe() + { + using var dir = new TempDir(); + var file = new FileLog(dir.Path); + var log = new AppLog(file); + log.Info("AVVIO", "prova"); + await file.DisposeAsync(); + + var text = File.ReadAllText(file.PathFor("app", DateTime.Now)); + Assert.Contains("[AVVIO] prova", text); + } +} + +public class EnvConfigTests +{ + [Theory] + [InlineData("192.168.30.23", "192.168.30.23", null)] + [InlineData("192.168.30.23:5433", "192.168.30.23", 5433)] + [InlineData("postgres:5432", "postgres", 5432)] + [InlineData("[::1]:5432", "::1", 5432)] + [InlineData(" ", "", null)] + public void DB_HOST_accetta_anche_la_porta(string raw, string host, int? port) + { + var (h, p) = EnvConfig.SplitHost(raw); + Assert.Equal(host, h); + Assert.Equal(port, p); + } + + [Fact] + public void Predefiniti_e_porta_separata() + { + var env = new Dictionary { ["DB_HOST"] = "db", ["DB_PORT"] = "6000", ["DB_PASSWORD"] = "x" }; + var cfg = EnvConfig.Read(k => env.GetValueOrDefault(k), Array.Empty()); + Assert.Equal("db", cfg.DbHost); + Assert.Equal(6000, cfg.DbPort); + Assert.Equal("admin", cfg.DbUser); + Assert.Equal("autobidder", cfg.DbName); + Assert.Equal(8080, cfg.HttpPort); + Assert.False(cfg.HasUiPassword); + Assert.Equal("/config", cfg.ConfigDir); + Assert.DoesNotContain("x", cfg.ToDbConfig().Describe()); + } +} + +/// Avvio senza variabili: schermata d'errore, niente database (ConfigErrorTests della specifica). +public class ConfigErrorTests +{ + [Fact] + public async Task Senza_variabili_il_rapporto_dice_cosa_manca() + { + using var dir = new TempDir(); + var env = EnvConfig.Read(_ => null, new[] { "--config", dir.Path }); + var (report, db) = await StartupCheck.RunAsync(env, new ConfigPaths(dir.Path), 1, CancellationToken.None); + + Assert.Null(db); + Assert.False(report.AllOk); + Assert.Contains(report.Items, i => i.Key == "db_host" && !i.Ok); + Assert.Contains(report.Items, i => i.Key == "db_password" && !i.Ok); + Assert.Contains(report.Items, i => i.Key == "ui_password" && !i.Ok); + Assert.Contains(report.Items, i => i.Key == "config" && i.Ok); + } + + [Fact] + public async Task Database_irraggiungibile_da_un_errore_leggibile() + { + using var dir = new TempDir(); + var vars = new Dictionary { ["DB_HOST"] = "127.0.0.1:1", ["DB_PASSWORD"] = "segreta", ["UI_PASSWORD"] = "x" }; + var env = EnvConfig.Read(k => vars.GetValueOrDefault(k), new[] { "--config", dir.Path }); + var (report, db) = await StartupCheck.RunAsync(env, new ConfigPaths(dir.Path), 1, CancellationToken.None); + + Assert.Null(db); + var item = Assert.Single(report.Items, i => i.Key == "database"); + Assert.False(item.Ok); + Assert.StartsWith("Npgsql:", item.Error); + Assert.DoesNotContain("segreta", item.Error + item.Detail); + + var html = Pages.ConfigError("1.0.0", report, 30); + Assert.Contains("Bidoo BidBot non può partire", html); + Assert.Contains("Riprova adesso", html); + Assert.DoesNotContain("segreta", html); + } +} + +public class UiAuthTests +{ + private static UiAuth Make(string password = "giusta") => new(password, new byte[32]); + + [Fact] + public void Solo_la_password_giusta_passa() + { + var auth = Make(); + Assert.True(auth.CheckPassword("giusta")); + Assert.False(auth.CheckPassword("Giusta")); + Assert.False(auth.CheckPassword("")); + Assert.False(auth.CheckPassword(null)); + } + + [Fact] + public void Il_cookie_vale_30_giorni_e_poi_scade() + { + var auth = Make(); + var now = new DateTimeOffset(2026, 9, 26, 12, 0, 0, TimeSpan.Zero); + var token = auth.IssueToken(now); + + Assert.True(auth.Validate(token, now.AddDays(29)).Valid); + Assert.False(auth.Validate(token, now.AddDays(31)).Valid); + Assert.True(auth.Validate(token, now.AddDays(2)).ShouldRenew); + Assert.False(auth.Validate(token, now.AddHours(2)).ShouldRenew); + } + + [Fact] + public void Un_cookie_alterato_o_di_un_altra_password_non_vale() + { + var now = DateTimeOffset.UtcNow; + var token = Make().IssueToken(now); + + Assert.False(Make("altra").Validate(token, now).Valid); + Assert.False(Make().Validate(token[..^2] + "AA", now).Valid); + Assert.False(Make().Validate("spazzatura", now).Valid); + Assert.False(Make().Validate(null, now).Valid); + } + + [Fact] + public void Dopo_cinque_tentativi_l_attesa_cresce() + { + var auth = Make(); + var now = DateTimeOffset.UtcNow; + for (var i = 0; i < 4; i++) Assert.Equal(TimeSpan.Zero, auth.RecordFailure("1.2.3.4", now)); + + Assert.Equal(TimeSpan.FromSeconds(2), auth.RecordFailure("1.2.3.4", now)); + Assert.Equal(TimeSpan.FromSeconds(4), auth.RecordFailure("1.2.3.4", now)); + Assert.Equal(TimeSpan.FromSeconds(8), auth.RecordFailure("1.2.3.4", now)); + Assert.True(auth.LockedFor("1.2.3.4", now) > TimeSpan.Zero); + Assert.Equal(TimeSpan.Zero, auth.LockedFor("5.6.7.8", now)); + + auth.RecordSuccess("1.2.3.4"); + Assert.Equal(TimeSpan.Zero, auth.LockedFor("1.2.3.4", now)); + } + + [Fact] + public void La_chiave_si_crea_una_volta_e_si_rilegge() + { + using var dir = new TempDir(); + var file = Path.Combine(dir.Path, "sessione", "interfaccia.key"); + var a = UiAuth.LoadOrCreateKey(file); + var b = UiAuth.LoadOrCreateKey(file); + Assert.Equal(32, a.Length); + Assert.Equal(a, b); + } +} + +/// Impostazioni: valori di fabbrica, migrazione, conferma DAL VIVO, segreti (SettingsMigrationTests). +public class SettingsTests +{ + private static Dictionary Patch(string json) => + JsonSerializer.Deserialize>(json)!; + + [Fact] + public void I_paletti_di_fabbrica_sono_tutti_a_zero() + { + var s = new AppSettings(); + Assert.Equal(0, s.DefaultMaxPrice); + Assert.Equal(0, s.MaxBidsPerAuction); + Assert.Equal(0, s.MinimumRemainingBids); + Assert.Equal(0, s.DailyBudgetEuro); + Assert.False(s.QuietHoursEnabled); + Assert.False(s.LiveBiddingEnabled); + Assert.Equal(300, s.LearningMinAuctions); + Assert.Equal(50, s.DataCapGb); + Assert.Equal("Osserva", s.AutoAddNewAuctionState); + } + + [Fact] + public void La_migrazione_porta_i_modi_in_italiano() + { + var s = new AppSettings { SettingsSchemaVersion = 0, AutoAddNewAuctionState = "Watch", DefaultStartAuctionsOnLoad = "Stopped", DefaultNewAuctionState = "Active" }; + Assert.True(SettingsStore.Migrate(s)); + Assert.Equal("Osserva", s.AutoAddNewAuctionState); + Assert.Equal("Ferma", s.DefaultStartAuctionsOnLoad); + Assert.Equal("Attiva", s.DefaultNewAuctionState); + Assert.False(SettingsStore.Migrate(s)); + } + + [Fact] + public void I_valori_fuori_scala_si_riportano_nei_limiti() + { + var s = SettingsStore.Normalize(new AppSettings { LeadMinMs = 10, LeadMaxMs = 5, QuietHoursStart = 25, DataCapGb = 0, PollCriticalMs = 1 }); + Assert.Equal(100, s.LeadMinMs); + Assert.Equal(100, s.LeadMaxMs); + Assert.Equal(1, s.QuietHoursStart); + Assert.Equal(1, s.DataCapGb); + Assert.Equal(50, s.PollCriticalMs); + } + + [Fact] + public async Task Il_salvataggio_vale_subito_e_si_scrive_nel_registro() + { + var log = new AppLog(null); + var store = new SettingsStore(null, log); + var result = await store.SaveAsync(Patch("""{"DailyBudgetEuro": 15, "MaxBidsPerAuction": 25}"""), null); + + Assert.True(result.Ok); + Assert.Equal(15, store.Current.DailyBudgetEuro); + Assert.Equal(2, result.Changes.Count); + Assert.Contains(log.Snapshot(), e => e.Tag == "IMPOSTAZIONI" && e.Message.StartsWith("DailyBudgetEuro: 0 -> 15")); + } + + [Fact] + public async Task Per_puntare_dal_vivo_serve_la_parola() + { + var store = new SettingsStore(null, null); + + var denied = await store.SaveAsync(Patch("""{"LiveBiddingEnabled": true}"""), "si"); + Assert.False(denied.Ok); + Assert.False(store.Current.LiveBiddingEnabled); + + var ok = await store.SaveAsync(Patch("""{"LiveBiddingEnabled": true}"""), "DAL VIVO"); + Assert.True(ok.Ok); + Assert.True(store.Current.LiveBiddingEnabled); + + // Spegnere non chiede conferme. + var off = await store.SaveAsync(Patch("""{"LiveBiddingEnabled": false}"""), null); + Assert.True(off.Ok); + Assert.False(store.Current.LiveBiddingEnabled); + } + + [Fact] + public async Task I_segreti_non_finiscono_nel_registro_e_tornano_mascherati() + { + var log = new AppLog(null); + var store = new SettingsStore(null, log); + await store.SaveAsync(Patch("""{"TelegramBotToken": "123:segretissimo"}"""), null); + + Assert.DoesNotContain(log.Snapshot(), e => e.Message.Contains("segretissimo")); + Assert.Equal(SettingsStore.MaskedSecret, SettingsStore.ForDisplay(store.Current)["TelegramBotToken"]); + + // Il valore mascherato che torna dall'interfaccia lascia il segreto com'era. + await store.SaveAsync(Patch("""{"TelegramBotToken": "********", "TelegramChatId": "42"}"""), null); + Assert.Equal("123:segretissimo", store.Current.TelegramBotToken); + } + + [Fact] + public async Task Una_chiave_sconosciuta_o_un_tipo_sbagliato_non_si_salvano() + { + var store = new SettingsStore(null, null); + Assert.False((await store.SaveAsync(Patch("""{"NonEsiste": 1}"""), null)).Ok); + Assert.False((await store.SaveAsync(Patch("""{"DailyBudgetEuro": "tanto"}"""), null)).Ok); + Assert.Equal(0, store.Current.DailyBudgetEuro); + } +} diff --git a/Mimante/tests/BidooBidBot.Tests/TestSupport.cs b/Mimante/tests/BidooBidBot.Tests/TestSupport.cs new file mode 100644 index 0000000..d189a35 --- /dev/null +++ b/Mimante/tests/BidooBidBot.Tests/TestSupport.cs @@ -0,0 +1,105 @@ +using System.Globalization; +using System.Runtime.CompilerServices; +using BidooBidBot.Data; +using Npgsql; +using Xunit; + +namespace BidooBidBot.Tests; + +/// Numeri all'italiana anche nei test: i messaggi del bot si leggono così. +internal static class TestCulture +{ + [ModuleInitializer] + internal static void Init() + { + CultureInfo.DefaultThreadCurrentCulture = CultureInfo.GetCultureInfo("it-IT"); + CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.GetCultureInfo("it-IT"); + CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("it-IT"); + } +} + +/// +/// Il PostgreSQL dei test, da TEST_DB_HOST (più TEST_DB_USER, +/// TEST_DB_PASSWORD, TEST_DB_NAME). Senza la variabile i test su database +/// saltano: in locale basta il compose di tools/dev, nel workflow c'è il servizio. +/// +public static class TestDb +{ + public static string? Host => Environment.GetEnvironmentVariable("TEST_DB_HOST") is { Length: > 0 } h ? h : null; + + public static DbConfig Config => new( + Host ?? "localhost", + 5432, + Environment.GetEnvironmentVariable("TEST_DB_USER") ?? "admin", + Environment.GetEnvironmentVariable("TEST_DB_PASSWORD") ?? "dev", + Environment.GetEnvironmentVariable("TEST_DB_NAME") ?? "bidbot_test"); +} + +/// Un test su PostgreSQL: salta se TEST_DB_HOST non è impostata. +public sealed class DbFactAttribute : FactAttribute +{ + public DbFactAttribute() + { + if (TestDb.Host == null) Skip = "TEST_DB_HOST non impostata: test su PostgreSQL saltato"; + } +} + +/// +/// Database di prova pulito, una volta per esecuzione: si cancella e si ricrea, poi si +/// applicano le migrazioni. I test della collezione «Database» girano uno alla volta. +/// +public sealed class DatabaseFixture : IAsyncLifetime +{ + public Db? Db { get; private set; } + + public async Task InitializeAsync() + { + if (TestDb.Host == null) return; + + var cfg = TestDb.Config; + await using (var admin = new NpgsqlConnection(cfg.Builder("postgres").ConnectionString)) + { + await admin.OpenAsync(); + var name = cfg.Database.Replace("\"", "\"\"", StringComparison.Ordinal); + await using (var drop = new NpgsqlCommand($"DROP DATABASE IF EXISTS \"{name}\" WITH (FORCE)", admin)) + await drop.ExecuteNonQueryAsync(); + await using (var create = new NpgsqlCommand($"CREATE DATABASE \"{name}\"", admin)) + await create.ExecuteNonQueryAsync(); + } + + Db = new Db(cfg); + await Migrations.ApplyAsync(Db.Writer); + await Partitions.EnsureAsync(Db, DateTime.UtcNow); + } + + public async Task DisposeAsync() + { + if (Db != null) await Db.DisposeAsync(); + } + + /// Svuota le tabelle fra un test e l'altro (le partizioni restano). + public async Task TruncateAsync() + { + await Db!.ExecuteAsync( + "TRUNCATE settings, documents, items, auctions, bids, resets, my_bids, bot_decisions, auction_forecasts, " + + "bidders, risk_ledger, products, watched_products, product_stats RESTART IDENTITY CASCADE"); + } +} + +[CollectionDefinition("Database")] +public sealed class DatabaseCollection : ICollectionFixture +{ +} + +/// Cartella temporanea che si cancella da sola: i test non scrivono mai altrove. +public sealed class TempDir : IDisposable +{ + public string Path { get; } = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "bidbot-test-" + Guid.NewGuid().ToString("N")[..10]); + + public TempDir() => Directory.CreateDirectory(Path); + + public void Dispose() + { + try { Directory.Delete(Path, true); } catch { } + } +} diff --git a/Mimante/tools/dev/docker-compose.yml b/Mimante/tools/dev/docker-compose.yml new file mode 100644 index 0000000..e06ff21 --- /dev/null +++ b/Mimante/tools/dev/docker-compose.yml @@ -0,0 +1,72 @@ +# Sviluppo locale di Bidoo BidBot: PostgreSQL 18 come su Unraid, e il bot dal Dockerfile. +# +# docker compose -f tools/dev/docker-compose.yml up -d postgres # solo il database +# docker compose -f tools/dev/docker-compose.yml up -d --build # database + bot +# docker compose -f tools/dev/docker-compose.yml --profile simulatore up -d --build +# +# Il bot legge /config da tools/dev/config (ignorata da git). Interfaccia: http://localhost:8080, +# password «dev». Fuori da Docker: DB_HOST=localhost DB_PASSWORD=dev UI_PASSWORD=dev +# dotnet run --project src/BidooBidBot -- --config tools/dev/config +name: bidoo-bidbot-dev + +services: + postgres: + image: postgres:18 + environment: + POSTGRES_USER: admin + POSTGRES_PASSWORD: dev + POSTGRES_DB: autobidder + ports: + - "5432:5432" + volumes: + - pgdata:/var/lib/postgresql + healthcheck: + test: ["CMD-SHELL", "pg_isready -U admin -d autobidder"] + interval: 5s + retries: 20 + + bot: + build: + context: ../.. + dockerfile: docker/Dockerfile + args: + VERSION: dev + depends_on: + postgres: + condition: service_healthy + environment: + DB_HOST: postgres:5432 + DB_PASSWORD: dev + UI_PASSWORD: dev + TZ: Europe/Rome + PUID: "1000" + PGID: "1000" + ports: + - "8080:8080" + volumes: + - ./config:/config + + # Lo stesso bot, senza sessione Bidoo: parte in modalità simulatore (banner in alto). + bot-simulatore: + profiles: ["simulatore"] + build: + context: ../.. + dockerfile: docker/Dockerfile + args: + VERSION: dev + depends_on: + postgres: + condition: service_healthy + environment: + DB_HOST: postgres:5432 + DB_NAME: bidbot_simulatore + DB_PASSWORD: dev + UI_PASSWORD: dev + TZ: Europe/Rome + ports: + - "8081:8080" + volumes: + - ./config-simulatore:/config + +volumes: + pgdata: diff --git a/Mimante/unraid/bidoo-bidbot.xml b/Mimante/unraid/bidoo-bidbot.xml new file mode 100644 index 0000000..0fe6605 --- /dev/null +++ b/Mimante/unraid/bidoo-bidbot.xml @@ -0,0 +1,34 @@ + + + bidoo-bidbot + 192.168.30.23:3000/alby96/bidoo-bidbot:latest + http://192.168.30.23:3000/Alby96/-/packages/container/bidoo-bidbot + bridge + + bash + false + http://192.168.30.23:3000/Alby96/bidoo-bidbot/issues + http://192.168.30.23:3000/Alby96/bidoo-bidbot + Bidoo BidBot: segue le aste al centesimo di Bidoo, decide con un modello appreso se puntare e punta negli ultimi millisecondi. Parte in modalita' OSSERVA (nessuna puntata reale). Richiede il container PostgreSQL (postgresql18) e una password per l'interfaccia. Interfaccia web sulla porta 8080, notifiche Telegram. Registry in HTTP: aggiungi --insecure-registry 192.168.30.23:3000 in DOCKER_OPTS (/boot/config/docker.cfg). Uso personale: rispetta i Termini di Bidoo, un solo account. + Tools: Productivity: + http://[IP]:[PORT:8080]/ + http://192.168.30.23:3000/Alby96/bidoo-bidbot/raw/branch/main/unraid/bidoo-bidbot.xml + http://192.168.30.23:3000/Alby96/bidoo-bidbot/raw/branch/main/docs/icona.png + --memory=1g --restart=unless-stopped --stop-timeout 15 + + + + + + Il container PostgreSQL (postgresql18, utente admin, database autobidder) raggiungibile dal bot. + 8080 + /mnt/user/appdata/bidoo-bidbot + 192.168.30.23:5432 + + + admin + autobidder + Europe/Rome + 99 + 100 +