diff --git a/.github/scripts/check-yaml.rb b/.github/scripts/check-yaml.rb new file mode 100644 index 00000000..8e82d3c1 --- /dev/null +++ b/.github/scripts/check-yaml.rb @@ -0,0 +1,42 @@ +# Parses YAML files and checks the shape of GitHub issue forms, so a broken workflow, compose file or issue form fails +# CI instead of being skipped by GitHub (an issue form that does not parse is simply not offered). +# Usage: ruby .github/scripts/check-yaml.rb FILE... +require "yaml" + +def issue_form_problem(doc) + return "the form is not a mapping" unless doc.is_a?(Hash) + return "the form needs a name and a description" unless doc["name"].is_a?(String) && doc["description"].is_a?(String) + return "the form needs a body list" unless doc["body"].is_a?(Array) && !doc["body"].empty? + + ids = [] + doc["body"].each_with_index do |item, i| + return "body item #{i + 1} has no type" unless item.is_a?(Hash) && item["type"].is_a?(String) + + attributes = item["attributes"] + return "body item #{i + 1} has no attributes" unless attributes.is_a?(Hash) + + if item["type"] == "markdown" + return "markdown item #{i + 1} has no value" unless attributes["value"].is_a?(String) + else + return "body item #{i + 1} has no label" unless attributes["label"].is_a?(String) + ids << item["id"] if item["id"] + end + end + return "duplicate ids #{ids.tally.select { |_, n| n > 1 }.keys.join(', ')}" if ids.uniq.size != ids.size + + nil +end + +failures = 0 +ARGV.each do |path| + doc = YAML.safe_load(File.read(path), aliases: true, filename: path) + if File.basename(File.dirname(path)) == "ISSUE_TEMPLATE" && File.basename(path) != "config.yml" + problem = issue_form_problem(doc) + raise problem if problem + end + puts "ok #{path}" +rescue StandardError => e + puts "::error file=#{path},title=YAML::#{e.message.lines.first.to_s.strip}" + failures += 1 +end +exit(failures.zero? ? 0 : 1) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 926ad0c4..1b556aeb 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -64,10 +64,14 @@ jobs: if: runner.os == 'Windows' run: dotnet format whitespace Titano.slnx --verify-no-changes + # GitHub silently skips a workflow or issue form that does not parse; the public issue forms ship with releases. + - name: YAML check (workflows, compose, public issue forms) + if: runner.os == 'Linux' + run: ruby .github/scripts/check-yaml.rb .github/workflows/*.yml deploy/docker/docker-compose.yml deploy/releases-repo/.github/ISSUE_TEMPLATE/*.yml + + # Missing samples become "RAW fixture missing" warning annotations; the tests that need them skip. - name: Fetch CC0 fixtures - continue-on-error: true - run: | - if dotnet "$TOOLS" --help | grep -q '^ fixtures'; then dotnet "$TOOLS" fixtures; fi + run: dotnet "$TOOLS" fixtures --allow-missing - name: Test · Core run: dotnet run --project tests/Titano.Core.Tests -c Release --no-build -- --junit out/junit/core.xml @@ -78,6 +82,9 @@ jobs: - name: Test · Server run: dotnet run --project tests/Titano.Server.Tests -c Release --no-build -- --junit out/junit/server.xml + - name: Test · Tools + run: dotnet run --project tests/Titano.Tools.Tests -c Release --no-build -- --junit out/junit/tools.xml + - name: Test · Core.Windows if: runner.os == 'Windows' run: dotnet run --project tests/Titano.Core.Windows.Tests -c Release --no-build -- --junit out/junit/core-windows.xml @@ -88,6 +95,7 @@ jobs: - name: Screenshots if: runner.os == 'Windows' + timeout-minutes: 10 run: | set +e for exe in src/Titano.App/bin/Release/net10.0-windows/Titano.exe src/Titano.Uploader/bin/Release/net10.0-windows/Titano.Uploader.exe; do diff --git a/.github/workflows/perf.yml b/.github/workflows/perf.yml new file mode 100644 index 00000000..0a8f0e75 --- /dev/null +++ b/.github/workflows/perf.yml @@ -0,0 +1,77 @@ +name: Performance gates + +# BRIEF §1.1 and the Phase 2/3 gates on a synthetic 500,000-photo library (SQLite and PostgreSQL 17) and a +# 100,000-frame archive rebuild from sidecars. Too slow for every push: weekly and on demand. +on: + schedule: + - cron: "41 3 * * 1" + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: perf-${{ github.ref }} + cancel-in-progress: true + +env: + DOTNET_NOLOGO: "1" + DOTNET_CLI_TELEMETRY_OPTOUT: "1" + +jobs: + perf: + name: Library and rebuild gates + runs-on: ubuntu-latest + timeout-minutes: 90 + services: + postgres: + image: postgres:17 + env: + POSTGRES_USER: titano + POSTGRES_PASSWORD: titano-ci + POSTGRES_DB: titano_perf + ports: + - 5432:5432 + options: >- + --health-cmd "pg_isready -U titano -d titano_perf" + --health-interval 5s --health-timeout 5s --health-retries 20 + env: + TITANO_PERF: "1" + TITANO_TEST_PG: Host=127.0.0.1;Port=5432;Database=titano_perf;Username=titano;Password=titano-ci;SslMode=disable + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-dotnet@v4 + with: + global-json-file: global.json + + - name: Build + run: dotnet build tests/Titano.Data.Tests -c Release + + - name: Perf tests (SQLite, PostgreSQL 17) + run: | + set -o pipefail + dotnet run --project tests/Titano.Data.Tests -c Release --no-build -- --filter category:perf --verbose --junit out/junit/perf.xml | tee out-perf.log + + - name: Timings + if: always() + run: | + { + echo "## Performance gates" + echo '```' + if grep -q "perf:" out-perf.log 2>/dev/null; then + grep -h "perf:" out-perf.log | sed 's/^ *//' + else + echo "no timings recorded" + fi + echo '```' + } >> "$GITHUB_STEP_SUMMARY" + + - name: Upload results + if: always() + uses: actions/upload-artifact@v4 + with: + name: perf-results + path: | + out/junit/ + out-perf.log + if-no-files-found: ignore diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 03ecd78e..f07db794 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,5 +1,8 @@ name: Release +# A tag vMAJOR.MINOR.PATCH[-PRERELEASE] builds, tests, signs (when certificates are configured) and publishes +# everything (BRIEF §19.3): installers, portable and server zips, SHA256SUMS, release notes, the multi-arch server +# image on GHCR, and the public releases repository content (BRIEF §19.4). on: push: tags: ["v*"] @@ -13,10 +16,16 @@ permissions: contents: write packages: write +concurrency: + group: release-${{ github.event.inputs.tag || github.ref_name }} + cancel-in-progress: false + env: DOTNET_NOLOGO: "1" DOTNET_CLI_TELEMETRY_OPTOUT: "1" - # Public repository that receives releases (BRIEF §19.4). Override with the RELEASES_REPO variable. + TOOLS: src/Titano.Tools/bin/Release/net10.0/Titano.Tools.dll + # Public repository that receives releases (BRIEF §19.4). Override with the RELEASES_REPO repository variable. Every + # build embeds it as TitanoReleasesRepo, so the update check, licence and issue links read the repository published to. RELEASES_REPO: ${{ vars.RELEASES_REPO || format('{0}/titano-releases', github.repository_owner) }} jobs: @@ -28,12 +37,19 @@ jobs: prerelease: ${{ steps.v.outputs.prerelease }} steps: - id: v + env: + TAG: ${{ github.event.inputs.tag || github.ref_name }} run: | - tag="${{ github.event.inputs.tag || github.ref_name }}" - version="${tag#v}" - echo "tag=$tag" >> "$GITHUB_OUTPUT" - echo "version=$version" >> "$GITHUB_OUTPUT" - if [[ "$version" == *-* ]]; then echo "prerelease=true" >> "$GITHUB_OUTPUT"; else echo "prerelease=false" >> "$GITHUB_OUTPUT"; fi + if [[ ! "$TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$ ]]; then + echo "::error title=Release::Tag '$TAG' is not vMAJOR.MINOR.PATCH or vMAJOR.MINOR.PATCH-PRERELEASE" + exit 1 + fi + version="${TAG#v}" + { + echo "tag=$TAG" + echo "version=$version" + if [[ "$version" == *-* ]]; then echo "prerelease=true"; else echo "prerelease=false"; fi + } >> "$GITHUB_OUTPUT" windows: needs: version @@ -43,6 +59,8 @@ jobs: shell: bash env: VERSION: ${{ needs.version.outputs.version }} + # Secrets cannot appear in step conditions: expose only whether signing is configured. + HAS_SIGNING: ${{ secrets.SIGN_PFX_BASE64 != '' }} steps: - uses: actions/checkout@v4 with: @@ -54,21 +72,31 @@ jobs: - name: Build and test run: | - dotnet build Titano.slnx -c Release -p:TitanoVersion="$VERSION" - for t in Core Data Server Core.Windows App; do + dotnet build Titano.slnx -c Release -p:TitanoVersion="$VERSION" -p:TitanoReleasesRepo="$RELEASES_REPO" + for t in Core Data Server Tools Core.Windows App; do dotnet run --project "tests/Titano.$t.Tests" -c Release --no-build -- --junit "out/junit/$t.xml" done + - name: Screenshots for the public README + continue-on-error: true + timeout-minutes: 10 + run: | + for exe in src/Titano.App/bin/Release/net10.0-windows/Titano.exe src/Titano.Uploader/bin/Release/net10.0-windows/Titano.Uploader.exe; do + "$exe" --capture out/screenshots & + wait $! || echo "::warning title=Screenshots::$(basename "$exe") --capture exited with $?" + done + ls out/screenshots + - name: Publish self-contained programs run: | - common="-c Release -r win-x64 --self-contained -p:TitanoVersion=$VERSION -p:PublishSingleFile=true -p:IncludeNativeLibrariesForSelfExtract=true -p:DebugType=none" + common="-c Release -r win-x64 --self-contained -p:TitanoVersion=$VERSION -p:TitanoReleasesRepo=$RELEASES_REPO -p:PublishSingleFile=true -p:IncludeNativeLibrariesForSelfExtract=true -p:DebugType=none" dotnet publish src/Titano.App/Titano.App.csproj $common -p:PublishReadyToRun=true -o out/publish/app dotnet publish src/Titano.Uploader/Titano.Uploader.csproj $common -p:PublishReadyToRun=true -o out/publish/uploader dotnet publish src/Titano.Server/Titano.Server.csproj $common -o out/publish/server dotnet publish src/Titano.Setup/Titano.Setup.csproj $common -p:PublishReadyToRun=true -o out/publish/setup - name: Sign binaries - if: env.SIGN_PFX != '' + if: env.HAS_SIGNING == 'true' env: SIGN_PFX: ${{ secrets.SIGN_PFX_BASE64 }} SIGN_PASSWORD: ${{ secrets.SIGN_PASSWORD }} @@ -76,27 +104,34 @@ jobs: run: | $pfx = Join-Path $env:RUNNER_TEMP "sign.pfx" [IO.File]::WriteAllBytes($pfx, [Convert]::FromBase64String($env:SIGN_PFX)) - $signtool = Get-ChildItem "${env:ProgramFiles(x86)}\Windows Kits\10\bin\*\x64\signtool.exe" | Sort-Object FullName -Descending | Select-Object -First 1 - Get-ChildItem out/publish -Recurse -Include *.exe | ForEach-Object { - & $signtool.FullName sign /fd SHA256 /f $pfx /p $env:SIGN_PASSWORD /tr http://timestamp.digicert.com /td SHA256 $_.FullName - if ($LASTEXITCODE -ne 0) { throw "signtool failed for $($_.FullName)" } + try { + $signtool = Get-ChildItem "${env:ProgramFiles(x86)}\Windows Kits\10\bin\*\x64\signtool.exe" | Sort-Object FullName -Descending | Select-Object -First 1 + if (-not $signtool) { throw "signtool.exe not found in the Windows SDK" } + Get-ChildItem out/publish -Recurse -Include *.exe | ForEach-Object { + & $signtool.FullName sign /fd SHA256 /f $pfx /p $env:SIGN_PASSWORD /tr http://timestamp.digicert.com /td SHA256 $_.FullName + if ($LASTEXITCODE -ne 0) { throw "signtool failed for $($_.FullName)" } + } + } finally { + Remove-Item $pfx -ErrorAction SilentlyContinue } - Remove-Item $pfx - name: Package installers and archives run: | mkdir -p out/release - tools=src/Titano.Tools/bin/Release/net10.0/Titano.Tools.dll - dotnet "$tools" pack-installer --setup out/publish/setup/Titano.Setup.exe --product Titano \ + dotnet "$TOOLS" pack-installer --setup out/publish/setup/Titano.Setup.exe --product Titano \ --component "Titano=out/publish/app" --component "Uploader=out/publish/uploader" --component "Server=out/publish/server" \ --version "$VERSION" --out "out/release/Titano-Setup-$VERSION.exe" - dotnet "$tools" pack-installer --setup out/publish/setup/Titano.Setup.exe --product "Titano Uploader" \ + dotnet "$TOOLS" pack-installer --setup out/publish/setup/Titano.Setup.exe --product "Titano Uploader" \ --component "Uploader=out/publish/uploader" --version "$VERSION" --out "out/release/Titano-Uploader-Setup-$VERSION.exe" (cd out/publish/server && 7z a -tzip "../../release/Titano-Server-win-x64-$VERSION.zip" . > /dev/null) - (cd out/publish/app && 7z a -tzip "../../release/Titano-win-x64-portable-$VERSION.zip" . > /dev/null) + # The portable build keeps its data next to Titano.exe because of portable.txt (never inside the installer). + cp -R out/publish/app out/portable + printf 'Titano portable mode: settings, index and logs are kept in the data folder next to Titano.exe.\r\n' > out/portable/portable.txt + (cd out/portable && 7z a -tzip "../release/Titano-win-x64-portable-$VERSION.zip" . > /dev/null) + ls -l out/release - name: Sign installers - if: env.SIGN_PFX != '' + if: env.HAS_SIGNING == 'true' env: SIGN_PFX: ${{ secrets.SIGN_PFX_BASE64 }} SIGN_PASSWORD: ${{ secrets.SIGN_PASSWORD }} @@ -104,27 +139,50 @@ jobs: run: | $pfx = Join-Path $env:RUNNER_TEMP "sign.pfx" [IO.File]::WriteAllBytes($pfx, [Convert]::FromBase64String($env:SIGN_PFX)) - $signtool = Get-ChildItem "${env:ProgramFiles(x86)}\Windows Kits\10\bin\*\x64\signtool.exe" | Sort-Object FullName -Descending | Select-Object -First 1 - Get-ChildItem out/release -Filter *.exe | ForEach-Object { & $signtool.FullName sign /fd SHA256 /f $pfx /p $env:SIGN_PASSWORD /tr http://timestamp.digicert.com /td SHA256 $_.FullName } - Remove-Item $pfx + try { + $signtool = Get-ChildItem "${env:ProgramFiles(x86)}\Windows Kits\10\bin\*\x64\signtool.exe" | Sort-Object FullName -Descending | Select-Object -First 1 + Get-ChildItem out/release -Filter *.exe | ForEach-Object { + & $signtool.FullName sign /fd SHA256 /f $pfx /p $env:SIGN_PASSWORD /tr http://timestamp.digicert.com /td SHA256 $_.FullName + if ($LASTEXITCODE -ne 0) { throw "signtool failed for $($_.FullName)" } + } + } finally { + Remove-Item $pfx -ErrorAction SilentlyContinue + } + + - name: Unsigned build notice + if: env.HAS_SIGNING != 'true' + run: echo "::notice title=Signing::SIGN_PFX_BASE64 is not set; the installers are unsigned." - name: Release notes + env: + TAG: ${{ needs.version.outputs.tag }} run: | - tag="${{ needs.version.outputs.tag }}" - previous="$(git describe --tags --abbrev=0 "$tag^" 2>/dev/null || true)" - range="${previous:+$previous..}$tag" - git log --format='%h%x09%s' "$range" | dotnet src/Titano.Tools/bin/Release/net10.0/Titano.Tools.dll changelog --title "Titano ${{ needs.version.outputs.version }}" --out out/release-notes.md + # A stable release lists everything since the previous stable one, not only what followed its last pre-release. + if [[ "$TAG" == *-* ]]; then + previous="$(git describe --tags --abbrev=0 "$TAG^" 2>/dev/null || true)" + else + previous="$(git describe --tags --abbrev=0 --exclude '*-*' "$TAG^" 2>/dev/null || true)" + fi + range="${previous:+$previous..}$TAG" + git log --no-merges --format='%h%x09%s' "$range" | dotnet "$TOOLS" changelog --title "Titano $VERSION" --out out/release-notes.md + cat out/release-notes.md - uses: actions/upload-artifact@v4 with: name: release-windows + if-no-files-found: error path: | out/release/ out/release-notes.md + out/screenshots/ + # Pushes only the version tag, and only after the Windows job's tests passed; publish moves :latest once the GitHub + # release exists and the tag is the newest stable one. docker: - needs: version + needs: [version, windows] runs-on: ubuntu-latest + outputs: + image: ${{ steps.image.outputs.name }} steps: - uses: actions/checkout@v4 with: @@ -146,9 +204,7 @@ jobs: platforms: linux/amd64,linux/arm64 push: true build-args: TITANO_VERSION=${{ needs.version.outputs.version }} - tags: | - ${{ steps.image.outputs.name }}:${{ needs.version.outputs.version }} - ${{ needs.version.outputs.prerelease == 'false' && format('{0}:latest', steps.image.outputs.name) || '' }} + tags: ${{ steps.image.outputs.name }}:${{ needs.version.outputs.version }} cache-from: type=gha cache-to: type=gha,mode=max @@ -158,49 +214,139 @@ jobs: env: TAG: ${{ needs.version.outputs.tag }} VERSION: ${{ needs.version.outputs.version }} + PRERELEASE: ${{ needs.version.outputs.prerelease }} + IMAGE: ${{ needs.docker.outputs.image }} + HAS_RELEASES_TOKEN: ${{ secrets.RELEASES_TOKEN != '' }} steps: - uses: actions/checkout@v4 with: ref: ${{ needs.version.outputs.tag }} + - uses: actions/setup-dotnet@v4 + with: + global-json-file: global.json - uses: actions/download-artifact@v4 with: name: release-windows path: out + - name: Checksums + working-directory: out/release run: | - cd out/release - sha256sum * > SHA256SUMS + rm -f SHA256SUMS + sha256sum -- * > "$RUNNER_TEMP/SHA256SUMS" + mv "$RUNNER_TEMP/SHA256SUMS" SHA256SUMS cat SHA256SUMS - - name: Create release in the public releases repository - if: env.RELEASES_TOKEN != '' + - name: Release target + id: target + env: + GH_TOKEN: ${{ env.HAS_RELEASES_TOKEN == 'true' && secrets.RELEASES_TOKEN || secrets.GITHUB_TOKEN }} + run: | + if [ "$HAS_RELEASES_TOKEN" = "true" ]; then + repo="$RELEASES_REPO" + else + repo="$GITHUB_REPOSITORY" + echo "::notice title=Release::RELEASES_TOKEN is not set: publishing to $GITHUB_REPOSITORY instead of $RELEASES_REPO (clients only see releases of $RELEASES_REPO)." + fi + # The public content (README, EULA, i18n/, SHA256SUMS), the GitHub "Latest" marker and the image's :latest tag + # follow the newest stable release, so re-publishing an older tag or publishing a pre-release never rolls them + # back; until a stable release exists, every tag updates the public content. + latest="$(gh release view --repo "$repo" --json tagName --jq .tagName 2>/dev/null || true)" + newest=true + if [ -n "$latest" ] && [ "$latest" != "$TAG" ]; then + if [ "$PRERELEASE" = "true" ] || [ "$(printf '%s\n%s\n' "${latest#v}" "$VERSION" | sort -V | tail -n 1)" != "$VERSION" ]; then + newest=false + fi + fi + echo "Latest release of $repo: ${latest:-none}; $TAG is the newest: $newest" + if [ "$newest" = "false" ]; then + echo "::notice title=Release::$TAG is older than $latest or a pre-release: the public repository content and :latest are left as they are." + fi + { + echo "repo=$repo" + echo "newest=$newest" + } >> "$GITHUB_OUTPUT" + + - name: Validate the public issue forms + run: ruby .github/scripts/check-yaml.rb deploy/releases-repo/.github/ISSUE_TEMPLATE/*.yml + + - name: GitHub release + env: + GH_TOKEN: ${{ env.HAS_RELEASES_TOKEN == 'true' && secrets.RELEASES_TOKEN || secrets.GITHUB_TOKEN }} + TARGET: ${{ steps.target.outputs.repo }} + NEWEST: ${{ steps.target.outputs.newest }} + run: | + # An older stable tag published again must not become "Latest" (the update check reads releases/latest). + latest=() + if [ "$PRERELEASE" = "false" ] && [ "$NEWEST" = "false" ]; then latest=(--latest=false); fi + if gh release view "$TAG" --repo "$TARGET" > /dev/null 2>&1; then + gh release upload "$TAG" out/release/* --repo "$TARGET" --clobber + gh release edit "$TAG" --repo "$TARGET" --title "Titano $VERSION" --notes-file out/release-notes.md --prerelease="$PRERELEASE" "${latest[@]}" + else + gh release create "$TAG" out/release/* --repo "$TARGET" --title "Titano $VERSION" --notes-file out/release-notes.md --prerelease="$PRERELEASE" "${latest[@]}" + fi + + - uses: docker/setup-buildx-action@v3 + if: env.PRERELEASE == 'false' && steps.target.outputs.newest == 'true' + - uses: docker/login-action@v3 + if: env.PRERELEASE == 'false' && steps.target.outputs.newest == 'true' + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + - name: Move the image's latest tag + if: env.PRERELEASE == 'false' && steps.target.outputs.newest == 'true' + # Compose and Unraid users follow :latest; it moves only once the release exists, never back to an older server. + run: docker buildx imagetools create --tag "$IMAGE:latest" "$IMAGE:$VERSION" + + - name: Update the public releases repository + if: env.HAS_RELEASES_TOKEN == 'true' && steps.target.outputs.newest == 'true' env: - RELEASES_TOKEN: ${{ secrets.RELEASES_TOKEN }} GH_TOKEN: ${{ secrets.RELEASES_TOKEN }} run: | - flags="" - if [ "${{ needs.version.outputs.prerelease }}" = "true" ]; then flags="--prerelease"; fi - gh release create "$TAG" out/release/* --repo "$RELEASES_REPO" --title "Titano $VERSION" --notes-file out/release-notes.md $flags - # Keep the Unraid template, icon and EULA in the public repository up to date. - git clone --depth 1 "https://x-access-token:${RELEASES_TOKEN}@github.com/${RELEASES_REPO}.git" public - mkdir -p public/unraid + branch="$(gh api "repos/$RELEASES_REPO" --jq .default_branch)" + git clone --depth 1 "https://x-access-token:${GH_TOKEN}@github.com/${RELEASES_REPO}.git" public + git -C public checkout -B "$branch" + cp -R deploy/releases-repo/. public/ + mkdir -p public/unraid public/docker public/screenshots cp deploy/unraid/titano.xml public/unraid/titano.xml + cp deploy/docker/docker-compose.yml deploy/docker/.env.example public/docker/ dotnet run --project src/Titano.Tools -c Release -- make-icon --out "$RUNNER_TEMP/icons" cp "$RUNNER_TEMP/icons/titano-server-256.png" public/unraid/titano-server.png - if [ -f docs/legal/EULA.md ]; then cp docs/legal/EULA.md public/EULA.md; fi + rm -rf public/i18n + cp -R i18n public/i18n + cp out/release/SHA256SUMS public/SHA256SUMS + for shot in library jobs settings-rendering server uploader-queue; do + if [ -f "out/screenshots/$shot-dark.png" ]; then cp "out/screenshots/$shot-dark.png" public/screenshots/; fi + done + # Links in the published files follow the configured repository and the image the docker job pushed. + find public -path public/.git -prune -o -type f \( -name '*.md' -o -name '*.yml' -o -name '*.xml' \) -print0 | + xargs -0 -r sed -i -e "s#alby96/titano-releases/main/#${RELEASES_REPO}/${branch}/#g" -e "s#alby96/titano-releases#${RELEASES_REPO}#g" \ + -e "s#ghcr.io/alby96/titano-server#${IMAGE}#g" cd public git config user.name "titano-release" git config user.email "titano-release@users.noreply.github.com" git add -A - git diff --cached --quiet || git commit -m "chore: update Unraid template and assets for $TAG" - git push + if git diff --cached --quiet; then + echo "Public repository already up to date." + else + git commit -q -m "chore: update for $TAG" + git push origin "HEAD:$branch" + fi - - name: Create release in this repository (no RELEASES_TOKEN configured) - if: env.RELEASES_TOKEN == '' + - name: Summary env: - RELEASES_TOKEN: ${{ secrets.RELEASES_TOKEN }} - GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + TARGET: ${{ steps.target.outputs.repo }} + NEWEST: ${{ steps.target.outputs.newest }} run: | - flags="" - if [ "${{ needs.version.outputs.prerelease }}" = "true" ]; then flags="--prerelease"; fi - gh release create "$TAG" out/release/* --repo "$GITHUB_REPOSITORY" --title "Titano $VERSION" --notes-file out/release-notes.md $flags + { + echo "## Titano $VERSION" + echo "- Release: https://github.com/$TARGET/releases/tag/$TAG" + echo "- Image: \`$IMAGE:$VERSION\`$([ "$PRERELEASE" = "false" ] && [ "$NEWEST" = "true" ] && echo " and \`:latest\`")" + echo "- GHCR packages are private when first pushed and GitHub has no API to change that: once, open the" + echo " package settings of \`titano-server\` and set its visibility to **Public** (BRIEF §19.4)." + echo + echo '```' + cat out/release/SHA256SUMS + echo '```' + } >> "$GITHUB_STEP_SUMMARY" diff --git a/README.md b/README.md index 39227d8e..de869086 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,123 @@ -# TimeLapseCreator -Desktop application for creating time lapse starting from a sequence +# Titano (development repository) + +Time-lapse ecosystem: **Titano** (Windows desktop client), **Titano Server** (Linux/Docker and Windows) and +**Titano Uploader** (Windows), sharing one C#/.NET 10 engine with zero third-party packages. This repository is +private; users get releases, the Docker image and the Unraid template from the public releases repository. + +- Specification: [`docs/BRIEF.md`](docs/BRIEF.md) · working rules: [`CLAUDE.md`](CLAUDE.md) +- Architecture and conventions: [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md) · decisions: + [`docs/DECISIONS.md`](docs/DECISIONS.md) · status: [`docs/STATUS.md`](docs/STATUS.md) · changes: + [`docs/CHANGELOG.md`](docs/CHANGELOG.md) +- Visual design: [`docs/ui/DESIGN.md`](docs/ui/DESIGN.md) and `docs/ui/mockups/` + +## Build, test, run + +Requirements: the .NET SDK pinned in `global.json`. Windows builds and runs everything; Linux builds everything +(the Windows projects for compile checking) and runs Core, Data, Protocol, Server and Tools. + +```sh +dotnet build Titano.slnx -c Release + +# Tests (one program per area; --filter text|category:name, --junit file, --verbose) +dotnet run --project tests/Titano.Core.Tests -c Release -- --junit out/core.xml +dotnet run --project tests/Titano.Data.Tests -c Release +dotnet run --project tests/Titano.Server.Tests -c Release +dotnet run --project tests/Titano.Tools.Tests -c Release +dotnet run --project tests/Titano.Core.Windows.Tests -c Release # Windows +dotnet run --project tests/Titano.App.Tests -c Release # Windows + +# PostgreSQL integration tests (16 or 17) +TITANO_TEST_PG="Host=127.0.0.1;Port=5432;Database=titano_test;Username=titano;Password=…;SslMode=disable" \ + dotnet run --project tests/Titano.Data.Tests -c Release + +# Performance gates (500,000-photo library, 100,000-frame rebuild; minutes) +TITANO_PERF=1 dotnet run --project tests/Titano.Data.Tests -c Release -- --filter category:perf --verbose + +# Checks run by CI +dotnet run --project src/Titano.Tools -- package-guard +dotnet run --project src/Titano.Tools -- i18n check +dotnet run --project src/Titano.Tools -- xaml-lint +dotnet format whitespace Titano.slnx --verify-no-changes + +# CC0 RAW samples for the decoder tests (tests/fixtures/manifest.json explains how to fill in URLs) +dotnet run --project src/Titano.Tools -- fixtures +``` + +Run: + +```sh +dotnet run --project src/Titano.Server # admin panel https://localhost:8443/admin +src/Titano.App/bin/Release/net10.0-windows/Titano.exe [--capture ] +src/Titano.Uploader/bin/Release/net10.0-windows/Titano.Uploader.exe +docker compose -f deploy/docker/docker-compose.yml up -d +``` + +The server reads `/data/server.json` (`TITANO_DATA_PATH`) and `TITANO_*` environment variables; +`Titano.Server --help` lists them. On Linux it needs PostgreSQL; on Windows it defaults to SQLite. + +## CI + +| Workflow | When | What | +|---|---|---| +| `.github/workflows/ci.yml` | push to `main`, pull requests | Windows + Linux build (warnings are errors), all tests, package guard, i18n check, XAML lint, format check, YAML check of workflows and public issue forms, CC0 fixtures (a warning per missing sample), screenshots (`--capture`, also pushed to the `ci-screenshots` branch for same-repository PRs), Windows program artifacts, PostgreSQL 16/17 integration, Docker image smoke test | +| `.github/workflows/docker.yml` | nightly | `ghcr.io//titano-server:nightly` (multi-arch) | +| `.github/workflows/perf.yml` | weekly, manual | Performance gates on SQLite and PostgreSQL 17; timings in the job summary | +| `.github/workflows/release.yml` | tag `v*`, manual re-publish | The release (below) | + +## Release process + +1. Make sure `main` is green and `docs/CHANGELOG.md` / `docs/STATUS.md` are up to date. +2. Tag and push: `git tag v0.2.0 && git push origin v0.2.0` (pre-releases: `v0.2.0-rc.1`; they are published as + GitHub pre-releases, get no `:latest` image and are ignored by the in-app update check). +3. `release.yml` then: + - validates the tag, builds with `TitanoVersion` from the tag and runs every test on Windows; + - publishes self-contained single-file programs, signs them when signing secrets exist, packs + `Titano-Setup-.exe` and `Titano-Uploader-Setup-.exe` (`Titano.Tools pack-installer`), signs the setups, + zips `Titano-Server-win-x64-.zip` and `Titano-win-x64-portable-.zip`; + - writes release notes from the Conventional Commits since the previous tag (`Titano.Tools changelog`); a stable + tag starts from the previous stable tag, so its notes include what its release candidates brought; + - once the Windows tests passed, builds and pushes `ghcr.io//titano-server:` for amd64 and arm64; + - computes `SHA256SUMS`, checks the public issue forms, creates (or updates) the GitHub release in the public + repository, then moves the image's `:latest` tag and updates the public repository content (README, EULA, + `i18n/`, `SHA256SUMS`). `:latest`, *Latest* and the content follow the newest stable release: a pre-release, or + an older tag published again, only gets its release and its `:` image. Until the first stable release exists, + every tag updates the content. +4. To publish an existing tag again (for example after adding a secret), run *Release* manually with the tag. + +### Secrets and variables + +| Name | Kind | Purpose | +|---|---|---| +| `RELEASES_TOKEN` | secret | Fine-grained PAT with *Contents: read and write* on the public releases repository. Without it the release is created in this (private) repository, which clients cannot see. | +| `RELEASES_REPO` | variable (optional) | `owner/name` of the public repository; default `/titano-releases`. `release.yml` passes it to every build as the `TitanoReleasesRepo` MSBuild property, so the update check, licence and issue links of the binaries read the repository the release goes to (local builds default to `alby96/titano-releases`). | +| `SIGN_PFX_BASE64` | secret (optional) | Base64 of the Authenticode code-signing certificate (`.pfx`). Without it builds are unsigned. | +| `SIGN_PASSWORD` | secret (optional) | Password of that `.pfx`. | + +`GITHUB_TOKEN` pushes the image to GHCR and moves its `:latest` tag; no other secret is used. + +### Bootstrapping the public releases repository + +1. Create a **public** repository named `titano-releases` under the same owner (or set `RELEASES_REPO`), with a + README so it has a default branch. Enable *Issues* and *Private vulnerability reporting* (Settings › Security). +2. Create the fine-grained PAT (repository access: only that repository; permissions: Contents read/write) and store + it as the `RELEASES_TOKEN` secret of this repository. +3. Push a pre-release tag (`v0.1.0-rc.1`). The release job copies `deploy/releases-repo/` (README, EULA draft, + SECURITY policy, issue forms), the Unraid template and its icon, the compose file and `.env.example`, the dark + screenshots, `i18n/` and the latest `SHA256SUMS` into the public repository after creating the release with the + installers, rewriting links to its name and default branch. +4. After the first image push, open the `titano-server` package on GHCR › *Package settings* and set its + visibility to **Public** (GitHub offers no API for this; the release summary reminds you). +5. Have the EULA draft (`deploy/releases-repo/EULA.md`) reviewed before the first stable release. +6. In Unraid, add `https://github.com//titano-releases` under Docker › Template repositories to validate the + template. + +## Repository layout + +``` +src/ Titano.Core, Core.Windows, Data, Protocol, Server, Ui, App, Uploader, Setup, Tools +tests/ Titano.Testing and one test program per area; fixtures/ (manifest of CC0 samples) +i18n/ /.resx string catalogs, GLOSSARY.md +deploy/ docker/ (Dockerfile, compose), unraid/ (template), releases-repo/ (public repository content) +branding/ SVG masters of the icons +docs/ BRIEF, ARCHITECTURE, DECISIONS, STATUS, CHANGELOG, ui/ +``` diff --git a/Titano.slnx b/Titano.slnx index 4ba03d78..eee03c3e 100644 --- a/Titano.slnx +++ b/Titano.slnx @@ -18,5 +18,6 @@ + diff --git a/deploy/releases-repo/.github/ISSUE_TEMPLATE/bug_report.yml b/deploy/releases-repo/.github/ISSUE_TEMPLATE/bug_report.yml new file mode 100644 index 00000000..770d90b9 --- /dev/null +++ b/deploy/releases-repo/.github/ISSUE_TEMPLATE/bug_report.yml @@ -0,0 +1,67 @@ +name: Bug report +description: Something in Titano, the Uploader or the Server does not work as expected. +title: "[Bug] " +labels: ["bug"] +body: + - type: markdown + attributes: + value: | + Thanks for taking the time. Security problems go to the *Security* tab (see SECURITY.md), not here. + - type: dropdown + id: program + attributes: + label: Program + options: + - Titano (desktop) + - Titano Uploader + - Titano Server (Docker / Unraid) + - Titano Server (Windows) + - Setup / update + validations: + required: true + - type: input + id: version + attributes: + label: Version + description: "About shows it (server: admin panel › About, or /api/v1/server/info)." + placeholder: "0.2.0" + validations: + required: true + - type: input + id: system + attributes: + label: System + description: Windows version, or the Docker/Unraid host and PostgreSQL version. + placeholder: "Windows 11 24H2, RTX 4070 / Unraid 7.0, PostgreSQL 17" + - type: textarea + id: what-happened + attributes: + label: What happened + description: What you did, what you expected and what happened instead. + validations: + required: true + - type: textarea + id: steps + attributes: + label: Steps to reproduce + placeholder: | + 1. Import a card with ... + 2. Open the sequence ... + 3. ... + - type: textarea + id: diagnostics + attributes: + label: Diagnostics + description: | + Desktop: Settings › Advanced › Diagnostics › *Export bundle* (or About › *Diagnostics bundle*), then drag the + zip here. Server: admin panel › Logs › *Diagnostics*. Bundles contain logs and system information, never photos, passwords or tokens; read them + before sharing if your folder or host names are private. + - type: checkboxes + id: checks + attributes: + label: Checks + options: + - label: I am using the latest release. + required: true + - label: I searched the existing issues. + required: true diff --git a/deploy/releases-repo/.github/ISSUE_TEMPLATE/config.yml b/deploy/releases-repo/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 00000000..06f85e6a --- /dev/null +++ b/deploy/releases-repo/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,5 @@ +blank_issues_enabled: false +contact_links: + - name: Report a security vulnerability + url: https://github.com/alby96/titano-releases/security/advisories/new + about: Please report security problems privately, never in a public issue. diff --git a/deploy/releases-repo/.github/ISSUE_TEMPLATE/translation_review.yml b/deploy/releases-repo/.github/ISSUE_TEMPLATE/translation_review.yml new file mode 100644 index 00000000..4ef53de2 --- /dev/null +++ b/deploy/releases-repo/.github/ISSUE_TEMPLATE/translation_review.yml @@ -0,0 +1,49 @@ +name: Translation review +description: A wrong, unclear or too long text in a translated version of Titano. +title: "[Translation] " +labels: ["translation"] +body: + - type: markdown + attributes: + value: | + Every language except English and Italian was machine-translated. Corrections from native speakers are very + welcome. The texts are in `i18n//..resx`; English sources are in `i18n/en/`. + Labels must stay short (at most about 30 characters), tooltips at most 200 characters, and placeholders such + as `{0}` must be kept. + - type: input + id: language + attributes: + label: Language + description: Language code as in the i18n folder. + placeholder: "de, fr, pt-BR, zh-Hans…" + validations: + required: true + - type: input + id: key + attributes: + label: Key + description: The `name` of the entry in the resx file, if you found it. Otherwise describe where the text appears. + placeholder: "Library.Filter.Year" + - type: textarea + id: current + attributes: + label: Current text + validations: + required: true + - type: textarea + id: proposal + attributes: + label: Proposed text + validations: + required: true + - type: textarea + id: context + attributes: + label: Context + description: Where the text appears (screen, button, tooltip) and why the proposal is better. A screenshot helps. + - type: checkboxes + id: native + attributes: + label: Reviewer + options: + - label: I am a native or fluent speaker of this language. diff --git a/deploy/releases-repo/EULA.md b/deploy/releases-repo/EULA.md new file mode 100644 index 00000000..9d22ddc6 --- /dev/null +++ b/deploy/releases-repo/EULA.md @@ -0,0 +1,108 @@ +# Titano — End User Licence Agreement + +> **DRAFT — not yet reviewed by a lawyer.** This text is a working draft prepared for the owner's legal review. It +> is published so that the terms intended for Titano are visible, but it may change before the first stable +> release. Where this draft is unclear or unenforceable, the mandatory law of your country applies. + +Version 0.1 (draft) · Applies to Titano, Titano Uploader and Titano Server ("the Software"), including their +installers, Docker images and updates. + +## 1. Who the parties are + +This agreement is between you (the person or organisation installing or using the Software) and the owner of the +Titano project ("the Licensor"). By installing, copying or using the Software you accept these terms. If you do not +accept them, do not install or use the Software. + +## 2. Licence granted + +The Licensor grants you a free of charge, non-exclusive, non-transferable, worldwide licence to: + +1. install and use the Software on any number of computers, servers and containers that you own or control, for + personal or commercial purposes, including producing and selling videos made with it; +2. make copies of the installers and images for backup and for deployment inside your own organisation. + +Everything you create with the Software — videos, images, projects, archives, reports — belongs to you. The +Licensor claims no rights over your content. + +## 3. Restrictions + +You may not: + +1. sell, rent, lease or sublicense the Software itself, or distribute modified copies of it; +2. remove or alter copyright notices, the licence text or the update and verification mechanisms; +3. reverse engineer, decompile or disassemble the Software, except to the extent that applicable law expressly + permits it despite this restriction (for example for interoperability); +4. use the Software in violation of applicable law, including laws on privacy and on the photographing of people + and places. + +Redistributing the unmodified installers, the `SHA256SUMS` file and the Docker image (for example in a mirror or a +NAS app catalogue) is allowed as long as they are offered free of charge and this agreement accompanies them. + +## 4. Your data and privacy + +The Software runs on your own computers and servers. It does not send your photos, videos, archive or account data +to the Licensor. The desktop programs contact the Internet only to: + +- check the public releases repository for a newer version and download it when you ask (Settings › Updates; can be + turned off); +- reach the Titano Server you configure; +- open links you click (in your browser). + +Optional anonymous usage counts, if enabled by you in Settings, contain no personal data, file names or content. +Diagnostics bundles are created only when you ask for one, are saved on your computer, and leave secrets (passwords, +tokens, keys) out; you decide whether to share them. + +## 5. Your responsibility for your files + +The Software is designed never to modify original photos and to verify copies by hash before anything is deleted +from a memory card. Nevertheless, you remain responsible for keeping independent backups of your data. Operations +that delete or move files (card formatting, deleting sequences, clearing caches) are always shown to you before they +run and require your explicit confirmation. + +## 6. Third-party components + +The Software contains no third-party libraries. It uses components of the operating system and of Microsoft .NET +(for example Windows Imaging Component and Media Foundation codecs, including codecs installed from the Microsoft +Store) under the terms that came with them. Formats such as H.264, HEVC and AV1 may be subject to patent licences; +encoders provided by Windows and by your graphics driver are licensed by their suppliers. + +## 7. Updates and support + +The Licensor may publish updates but is not obliged to provide updates, support or maintenance. Updates are +installed only when you run them. Support, if any, is offered through the public issue tracker. + +## 8. No warranty + +To the maximum extent permitted by applicable law, the Software is provided "as is", without warranty of any kind, +express or implied, including warranties of merchantability, fitness for a particular purpose, accuracy and +non-infringement. You use it at your own risk. + +## 9. Limitation of liability + +To the maximum extent permitted by applicable law, the Licensor is not liable for any indirect, incidental, special, +consequential or punitive damages, or for any loss of data, profits, revenue or business, arising out of the use of +or inability to use the Software, even if advised of the possibility of such damages. Where liability cannot be +excluded, it is limited to the amount you paid for the Software (which is zero). Nothing in this agreement limits +liability for wilful misconduct, gross negligence or anything else that cannot be limited by law, nor any rights +you have as a consumer that cannot be waived. + +## 10. Termination + +This licence ends automatically if you breach it. On termination you must stop using the Software and delete your +copies. Sections 4, 5, 8, 9 and 11 survive termination. Your content remains yours. + +## 11. Governing law + +This agreement is governed by the laws of Italy, without regard to its conflict-of-law rules; the courts of the +Licensor's place of residence have jurisdiction, unless mandatory consumer protection law of your country gives you +the right to sue at home. *(Draft note: jurisdiction to be confirmed by the owner.)* + +## 12. Future paid features + +Future versions may offer optional paid features or a supported edition under additional terms. Such terms will be +shown before you accept them and never apply retroactively to versions you already installed. + +## 13. Contact + +Questions about this agreement: open an issue in this repository or use the contact listed in +[SECURITY.md](SECURITY.md) for private matters. diff --git a/deploy/releases-repo/README.md b/deploy/releases-repo/README.md new file mode 100644 index 00000000..19fcefa7 --- /dev/null +++ b/deploy/releases-repo/README.md @@ -0,0 +1,120 @@ +# Titano + +Titano turns folders of photos (RAW, JPEG, HEIC…) into finished time-lapse videos and keeps a lifetime archive of +your shoots organised, verified and searchable — on one PC or on a shared server. + +This repository publishes the installers, the Docker image instructions, the Unraid template and the translations +for community review. Development happens elsewhere; please use the issues here for bugs and translation fixes. + +![Library](screenshots/library-dark.png) + +## Components + +| Program | Runs on | What it does | +|---|---|---| +| **Titano** | Windows 10 21H2+ / 11, x64 | Desktop client: card import with hash verification, archive, analysis advisor, sequence editor, rendering with GPU encoders (H.264, HEVC, AV1) | +| **Titano Uploader** | Windows 10 21H2+ / 11, x64 | Small tray program that uploads photos, folders, cards and watch folders to a Titano Server | +| **Titano Server** | Docker (linux/amd64, linux/arm64), Unraid, Windows | Shared archive, users, resumable uploads, sync, background jobs, render delegation to GPU-equipped PCs, web admin panel | + +| | | +|---|---| +| ![Jobs](screenshots/jobs-dark.png) | ![Rendering settings](screenshots/settings-rendering-dark.png) | +| ![Server](screenshots/server-dark.png) | ![Uploader](screenshots/uploader-queue-dark.png) | + +## Requirements + +- **Desktop programs:** Windows 10 version 21H2 or later, or Windows 11, 64-bit (x64). 8 GB of memory or more is + recommended for 4K renders. No other runtime is needed: the programs are self-contained. +- **Camera RAW files:** Titano develops DNG, CR2, NEF, ARW, PEF and RAF on its own. With Microsoft's free + *Raw Image Extension* installed, Windows' decoder is used first and covers the other formats (CR3, ORF, RW2…); + without it they render from the full-size preview embedded by the camera. HEIC needs Microsoft's *HEIF Image + Extensions* and *HEVC Video Extensions*. +- **Hardware encoding:** any GPU whose driver provides Media Foundation encoders (NVIDIA, AMD, Intel). Without one, + Titano encodes H.264 in software and its own formats (AVI, GIF, APNG, image sequences). +- **Server:** Docker 20.10+ (or Unraid 6.12+) and PostgreSQL 16 or 17; or Windows 10/11/Server 2019+ x64. + +## Install, upgrade, uninstall (Windows) + +1. Download `Titano-Setup-.exe` (Titano, Uploader and, optionally, Server) or + `Titano-Uploader-Setup-.exe` from the [latest release](../../releases/latest). +2. Check the download (optional, recommended): in PowerShell run + `Get-FileHash .\Titano-Setup-.exe -Algorithm SHA256` and compare the value with the line for that file + in `SHA256SUMS` of the same release. +3. Run the setup. It installs for the current user into `%LOCALAPPDATA%\Programs\Titano` without administrator + rights; choose *All users* to install into `Program Files` (Windows asks for permission). + +- **Upgrade:** Titano checks this repository at start (you can turn this off in Settings › Updates) and shows a notice + when a new version exists. *Download* fetches the setup, verifies it against `SHA256SUMS` and shows it in Explorer; + run it to upgrade in place. Your archive, settings and index are kept. +- **Uninstall:** Windows Settings › Apps › Installed apps › Titano › Uninstall. Your photos and archive are never + touched; the program data folder (`%LOCALAPPDATA%\Titano`) is removed only if you tick the option to do so. +- **Silent install** (IT deployment): `Titano-Setup-.exe /S [/DIR="D:\Apps\Titano"] [/ALLUSERS] + [/COMPONENTS=Titano,Uploader,Server] [/NODESKTOP] [/NOSTARTMENU] [/LANG=it]`. Silent uninstall: + `"%LOCALAPPDATA%\Programs\Titano\Uninstall Titano.exe" /uninstall /S`. +- **Portable:** `Titano-win-x64-portable-.zip` keeps its data in a `data` folder next to `Titano.exe` + (because of the `portable.txt` file). Do not unpack it into a OneDrive or Dropbox folder. + +## Titano Server with Docker Compose + +```sh +mkdir titano && cd titano +curl -LO https://raw.githubusercontent.com/alby96/titano-releases/main/docker/docker-compose.yml +curl -L -o .env https://raw.githubusercontent.com/alby96/titano-releases/main/docker/.env.example +# edit .env: TITANO_ADMIN_PASSWORD, TITANO_DB_PASSWORD, TITANO_ARCHIVE (folder of your archive), PUID/PGID, TZ +docker compose up -d +``` + +Open `http://:8080/admin`, sign in as `admin` with the password from `.env` and choose a new one. Titano +clients connect to `https://:8443`; the first connection shows the server's certificate fingerprint, which the +admin panel shows under Settings so you can compare them. + +- Image: `ghcr.io/alby96/titano-server:latest` (also `:`; `:nightly` follows development and is not for + production use). Multi-arch: `linux/amd64` and `linux/arm64`. +- Volumes: `/archive` (originals, sidecars, proxies, renders — the archive stays readable without Titano) and `/data` + (settings, TLS certificate, uploads in progress, logs). +- Upgrade: `docker compose pull && docker compose up -d`. Jobs in progress resume from their last checkpoint. +- All settings: environment variables `TITANO_*` (see `docker-compose.yml`) or `/data/server.json`. Run + `docker run --rm ghcr.io/alby96/titano-server:latest --help` for the list. + +## Titano Server on Unraid + +1. Install the official **postgresql17** template from Community Applications. Create a database `titano` owned by a + role `titano` (for example with `docker exec -it postgresql17 psql -U postgres -c "CREATE ROLE titano LOGIN + PASSWORD '…'" -c "CREATE DATABASE titano OWNER titano"`). +2. In Docker › *Template repositories* add `https://github.com/alby96/titano-releases` and save. +3. Docker › *Add container* › Template `titano-server`. Set the admin password, the database host (the PostgreSQL + container's name or IP), password and the archive share (default `/mnt/user/Timelapse`). +4. Open the WebUI (`http://[IP]:8080/admin`). + +The template file is [`unraid/titano.xml`](unraid/titano.xml). + +## Titano Server on Windows + +Unpack `Titano-Server-win-x64-.zip` (or choose the *Server* component in the setup). It uses SQLite in +`C:\ProgramData\Titano Server` by default, or PostgreSQL with `TITANO_DB=postgres` and the `TITANO_DB_*` variables. +Run `Titano.Server.exe` in a console, or install it as a Windows service from an administrator prompt with +`Titano.Server.exe --install-service` (remove it with `--uninstall-service`). + +## Translations + +Titano is written in English and Italian; every other language is machine-translated and marked as such in +About. The source strings are in [`i18n/`](i18n): `en/.resx` is the source, `/..resx` +the translation. To suggest a correction, open a **Translation review** issue with the key, the current text and +your proposal — or the in-app *Suggest a fix* link in About, which leads here. + +## Verifying downloads + +Every release carries `SHA256SUMS`. On Linux or macOS: `sha256sum -c SHA256SUMS --ignore-missing`. Titano's +in-app update download performs the same check before showing the setup or portable zip. Signed builds carry an Authenticode +signature; unsigned builds may show a SmartScreen prompt. + +## Support and security + +- Bugs: open a **Bug report** issue (attach the diagnostics bundle from Settings › Advanced › Diagnostics › + *Export bundle*, or the server's from admin panel › Logs › *Diagnostics*; it contains logs and system information, + never photos, passwords or tokens). +- Security problems: see [SECURITY.md](SECURITY.md) — please do not open public issues for them. + +## Licence + +Titano is proprietary software distributed free of charge under the [End User Licence Agreement](EULA.md). diff --git a/deploy/releases-repo/SECURITY.md b/deploy/releases-repo/SECURITY.md new file mode 100644 index 00000000..3bff6a19 --- /dev/null +++ b/deploy/releases-repo/SECURITY.md @@ -0,0 +1,48 @@ +# Security policy + +## Supported versions + +Security fixes are made for the latest release only. Upgrade before reporting a problem you found in an older +version; the in-app update check (Settings › Updates) and `docker compose pull` keep installations current. + +| Version | Supported | +|---|---| +| Latest release | Yes | +| Older releases, pre-releases, `:nightly` images | No | + +## Reporting a vulnerability + +Please **do not open a public issue** for a security problem. + +Use GitHub's private vulnerability reporting: *Security* tab of this repository › *Report a vulnerability*. Include: + +- the affected program (Titano, Uploader, Server) and version (About, or `/api/v1/server/info` for the server); +- how to reproduce the problem, and what an attacker gains; +- whether the server runs behind a reverse proxy and which TLS mode it uses (`auto`, `pem`, `proxy`). + +Do not attach diagnostics bundles or logs that you have not read: they are scrubbed of passwords and tokens, but +they contain host names, folder paths and user names. + +You will receive an acknowledgement within 7 days. Fixes are released as soon as they are ready, and the release +notes credit the reporter unless they prefer otherwise. Please give us 90 days, or until a fix is released, before +disclosing the problem publicly. + +## Scope + +In scope: the desktop programs, the installer, the server API and admin panel, the Docker image and the Unraid +template published here. + +Out of scope: problems that need an attacker who already controls the user's Windows account or the server host; +denial of service through unrealistic load; self-signed certificate warnings (the client pins the fingerprint you +confirm at first connection); findings from automated scanners without a demonstrated impact. + +## How Titano protects you + +- Releases list the SHA-256 of every file in `SHA256SUMS`; the in-app update download refuses a file whose hash does + not match. Builds are Authenticode-signed when a signing certificate is configured. +- The server stores passwords with PBKDF2-SHA512 (210,000 iterations) and session tokens only as SHA-256 hashes; + sign-in is rate limited and accounts lock after repeated failures. +- Desktop clients pin the server certificate fingerprint on first use, never send a saved token to a server whose + certificate changed, and keep tokens encrypted with Windows DPAPI. +- No program runs external tools or scripts; the only programs Titano starts are your browser (for links) and + Explorer (to show a folder). diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 8a51336d..3636cdd1 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -1,83 +1,184 @@ # Titano — Architecture and code conventions -Companion to `docs/BRIEF.md` (scope, behaviour) and `docs/ui/DESIGN.md` (looks). This file says -*where code goes* and *how it is written*. +Companion to `docs/BRIEF.md` (scope, behaviour) and `docs/ui/DESIGN.md` (looks). This file says *where code goes*, +*how data moves* and *how it is written*. Decisions behind the shapes described here are in `docs/DECISIONS.md`. ## 1. Projects | Project | TFM | Purpose | |---|---|---| -| `src/Titano.Core` | net10.0 | Engine shared by every program: metadata, codecs, imaging, analysis, motion, render, video containers, archive model, naming, import planning, localization runtime, brand mark | -| `src/Titano.Core.Windows` | net10.0-windows | WIC decoder, Media Foundation encoder, DXGI, device APIs, shell helpers (P/Invoke/COM only) | -| `src/Titano.Data` | net10.0 | `IDatabase`, SQLite binding (winsqlite3 on Windows, system libsqlite3 elsewhere for tests/dev), PostgreSQL wire client, migrations, repositories | -| `src/Titano.Protocol` | net10.0 | API DTOs, source-generated JSON contexts, upload/sync/event schemas | -| `src/Titano.Server` | net10.0 (Web SDK) | ASP.NET Core minimal API, auth, jobs, storage, admin web panel (embedded) | -| `src/Titano.Ui` | net10.0-windows (WPF) | Theme (DESIGN tokens), icons, custom controls, `Loc` markup extension, MVVM helpers | +| `src/Titano.Core` | net10.0 | Engine shared by every program: metadata, codecs, imaging, analysis, advisor, motion, render, video containers and managed encoders, archive format, naming, import planning, packaging, localization runtime, diagnostics, brand mark | +| `src/Titano.Core.Windows` | net10.0-windows | WIC decoders and codec inventory, Media Foundation encoders, DXGI adapters, removable devices, DPAPI, shell launcher, window chrome, power (P/Invoke/COM only) | +| `src/Titano.Data` | net10.0 | `IDatabase`, SQLite binding, PostgreSQL wire client, migrations, repositories, the job engine, the archive engine (`Archiving`) and the analysis/render engine (`Processing`) | +| `src/Titano.Protocol` | net10.0 | API v1 DTOs, source-generated JSON context, typed `TitanoClient` with certificate pinning and bandwidth limiting | +| `src/Titano.Server` | net10.0 (Web SDK) | ASP.NET Core minimal API, auth, uploads, sync, jobs, render nodes, events, embedded admin panel, Windows service host | +| `src/Titano.Ui` | net10.0-windows (WPF) | Theme (DESIGN tokens), icons, standard and custom controls, visuals (charts, filmstrip, preview, curve editor, virtualizing grid), `Loc` markup extension, MVVM helpers | | `src/Titano.App` | WPF exe `Titano.exe` | Desktop client | -| `src/Titano.Uploader` | WPF exe | Uploader | -| `src/Titano.Setup` | WPF exe | Installer/uninstaller | -| `src/Titano.Tools` | net10.0 exe | CLI: make-icon, i18n, xaml-lint, package-guard, selftest, diagnose, fixtures, changelog | -| `tests/Titano.Testing` | net10.0 | In-house test framework (`[Test]`, `[Theory]`+`[Case]`, `Assert`, `TestContext`) | +| `src/Titano.Uploader` | WPF exe | Uploader (tray, watch folders, resumable queue) | +| `src/Titano.Setup` | WPF exe | In-house installer/uninstaller (TPK1 payload) | +| `src/Titano.Tools` | net10.0 exe | CLI: `make-icon`, `i18n` (check, export, missing, import), `xaml-lint`, `package-guard`, `changelog`, `pack-installer`, `selftest`, `diagnose`, `fixtures` | +| `tests/Titano.Testing` | net10.0 | In-house test framework (`[Test]`, `[Theory]`+`[Case]`, `[Category]`, `[RequiresEnvironment]`, `[WindowsOnly]`, `[Serial]`, `Assert`, `TestContext`, JUnit) | | `tests/Titano.*.Tests` | exe | One test program per area; `dotnet run --project tests/X -- --junit out.xml` | -## 2. Namespaces in Titano.Core +Dependencies point one way: `Core` ← `Core.Windows`, `Data`, `Protocol` ← `Server`; `Ui` ← `App`, `Uploader`, `Setup`. +`Core`, `Data`, `Protocol` and `Server` never reference Windows-only code (Linux CI builds and tests them). + +## 2. Module map + +### 2.1 Titano.Core namespaces | Folder / namespace | Content | |---|---| -| `Imaging` | `ImageBuffer` (planar float, linear light), `ImageFileFormat`, `IImageDecoderProvider`, `ImageDecoder`, colour/geometry helpers, `FrameWindow` | -| `Metadata` (+ `Metadata.Tiff`, `Metadata.Bmff`, …) | Signature sniffing, TIFF/IFD (`TiffReader`), Exif/GPS/XMP/MakerNotes, ISO-BMFF, RIFF, RAF, PNG chunks, `MetadataReader`, `ExifWriter` | -| `Codecs` (`Codecs.Jpeg`, `Codecs.Png`, `Codecs.Tiff`, `Codecs.Dng`, `Codecs.Gif`, `Codecs.Ico`) | Pure managed image codecs | -| `Video` | `Mp4Muxer`, box writer, Annex-B/OBU parsing, MP4 inspector, AVI-MJPEG writer, managed encoder provider, encoder contracts | -| `Analysis` | Luminance statistics, deflicker, regions, holy grail, white balance, colour temperature, light/deep analysis | -| `Motion` | FFT, phase correlation, pyramids, optical flow, motion blur, stabilisation, virtual camera, interpolation, stacking | -| `Math` (namespace `Titano.Core.Mathematics`, so it never shadows `System.Math`) | Splines (Fritsch–Carlson, Catmull-Rom, Bézier), robust local regression, statistics, solar position, 3×3 colour matrices | -| `Render` | Render plan, pipeline, export presets | -| `Advisor` | Recommendation rules with localisable reasons, sequence presets | -| `Archive` | Archive layout, sidecars (`sequence.json`, `project.json`), scanner, rebuild, verify, duplicates, orphans, adopt | +| `Imaging` (+ `Decoders`, `Geometry`, `Thumbnails`) | `ImageBuffer` (planar float, linear light), `IImageDecoderProvider`, `DecoderFactory` (decode tiers: native → embedded preview), `ManagedDecoderProvider`, `FrameWindow` (read-ahead, memory budget, float32 spill), resampler, thumbnail cache | +| `Metadata` (+ `Tiff`, `Jpeg`, `Bmff`, `Raf`, `Riff`, `Png`, `Xmp`, `MakerNotes`) | Signature sniffing, Exif/GPS/XMP/MakerNotes, ISO-BMFF (HEIF, CR3), `MetadataReader`, `MetadataBuilder` (all fallback chains), `ExifWriter` | +| `Codecs` (`Jpeg`, `Png`, `Tiff`, `Dng`, `Raw`, `Gif`, `Apng`, `Ico`) | Pure managed codecs; native RAW development (DNG, CR2, NEF, ARW, PEF, RAF) | +| `Analysis` (+ `Deep`) | Luminance statistics, deflicker, regions, holy grail, white balance, colour temperature, light analysis, streaming deep analysis with checkpoints | +| `Advice` | `Advisor`: recommendations with localisable reasons, apply/optimise, sequence presets | +| `Motion` | FFT, phase correlation, pyramids, optical flow, motion blur, stabiliser, virtual camera, interpolation, stacking | +| `Math` (namespace `Titano.Core.Mathematics`) | Splines, LOWESS, statistics, solar position, 3×3 colour matrices | +| `Project` | `ProjectSettings` (Auto/manual values), export presets | +| `Render` | Render plan (timing modes), preparation pass, geometry, `RenderPipeline`, self-test suite | +| `Export` | Preset resolution, encoder selection with fallbacks, output naming | +| `Video` (+ `Mp4`, `Avi`, `Bitstream`, `Yuv`, `Managed`) | `IVideoEncoderProvider`, MP4 muxer and inspector, AVI-MJPEG, NV12/P010, managed encoders (MJPEG-AVI, GIF, APNG, image sequences) | +| `Archiving` | Archive layout and paths, sidecars (`sequence.json`, `project.json`), scanner, index snapshot, leases, thumbnail packs, verify, adopt, rename plans | +| `Import` | Card scan, session detection, import plan, hash-verified copy, card eraser (re-hash before delete) | | `Naming` | Folder/file templates and tokens | -| `Import` | Card/folder scan, session detection, import plan, hash-verified copy | -| `Model` | Domain entities (§5) shared by Data, Server and clients | -| `Localization`, `Diagnostics`, `IO`, `Hashing`, `Branding` | Infrastructure | +| `Model` | Domain entities and enums (§5) shared by Data, Server and clients | +| `Packaging` | TPK1 installer payload writer/reader, staged install transaction | +| `Diagnostics` | `Log`, file sink, synthetic sequences, `SecretScrubber`, `DiagnosticsArchive` (scrubbed diagnostics zip) | +| `Localization`, `IO`, `Hashing`, `Branding` | `Loc`/plural rules, `AtomicFile`, CRC-32/SHA helpers, brand mark geometry | -## 3. Conventions +### 2.2 Titano.Data + +| Folder | Content | +|---|---| +| `Sqlite`, `Postgres` | SQLite P/Invoke binding (winsqlite3 / libsqlite3), in-house PostgreSQL wire protocol v3 client with pool and LISTEN | +| `Migrations/{sqlite,postgres}/NNNN_name.sql` | Embedded, applied in one transaction at open (`MigrationRunner`) | +| `Repositories` | `TitanoDatabase` facade: archives, sequences, frames, tags, renders, jobs, cards, users, tokens, uploads, render nodes, settings, audit | +| `Jobs` | `JobEngine`, `IJobHandler`, `IJobHandlerProvider`, `JobContext` (progress, checkpoints, follow-up jobs) | +| `Archiving` | `ArchiveService` (create/adopt/open), `ArchiveIndexer` (scan, rebuild), `ArchiveIngest` (uploads and imports), `ImportService`, `ArchiveVerifier`, `ArchiveImages`, `ArchiveMaintenance`, `MassRenamer`, job handlers | +| `Processing` | `ProcessingService`, `SequenceAnalyser`, `SequenceRender`, `ProjectStore`, `RenderNodeClient`, job handlers | + +### 2.3 Hosts + +| Host | Composition root | What it runs | +|---|---|---| +| Titano (desktop) | `App/Infrastructure/AppServices` | SQLite index in `%LOCALAPPDATA%\Titano` (or `.\data` when portable); `ArchiveService` with WIC first, then managed decoders; `ProcessingService` with Media Foundation, then managed encoders; one `JobEngine` with the handlers of both; thumbnails; `ServerSession`; the render node while opted in and signed in; update check and download (`About/UpdateCheck`, `About/UpdateDownload`, `About/UpdateFlow`: the setup, or the portable zip for a portable copy, verified against `SHA256SUMS`, resumable, cancellable, failing after 60 s without data); diagnostics bundle | +| Titano Server | `Server/Hosting/ServerHost.Build` | Options from `server.json` + `TITANO_*`; PostgreSQL (or SQLite on Windows); `ArchiveModule` then `ProcessingModule` register job handler providers; `JobEngineHost` (never claims renders); `RenderNodeService`/`RenderNodeMonitor`; `UploadService`; `EventHub` (WebSocket); embedded admin panel; LAN discovery beacon; Windows service host | +| Titano Uploader | `Uploader/App.xaml.cs` | `TitanoClient`, persisted queue, watch folders; no database | +| Titano Setup | `Setup/Program` | TPK1 payload extraction, registry, shortcuts, silent mode, uninstaller | + +### 2.4 Job kinds and their handlers + +| `JobKind` | Handler (Titano.Data) | Desktop | Server | +|---|---|---|---| +| `Scan`, `Rebuild` | `Archiving/Jobs/ScanJobHandler` (via `ArchiveService.CreateJobHandlers`) | yes | yes | +| `Verify` | `Archiving/Jobs/VerifyJobHandler` | yes | yes | +| `Import` | `Archiving/Jobs/ImportJobHandler` | yes | yes | +| `Thumbs`, `Proxies` | `Archiving/Jobs/ImageJobHandler` | yes | yes | +| `Maintenance` | `Archiving/Jobs/MaintenanceJobHandler` | yes | yes | +| `LightAnalyse`, `DeepAnalyse` | `Processing/Jobs/AnalyseJobHandler` (via `ProcessingService.CreateJobHandlers`) | yes | yes | +| `Render` | `Processing/Jobs/RenderJobHandler` | yes | no: render nodes claim them (`Server/Jobs/RenderNodeService`) | +| `UploadCommit`, `Duplicates`, `Orphans`, `Adopt`, `Move` | none: done synchronously (upload completion, `ArchiveService` queries and actions) | — | — | + +A job engine claims only kinds it has handlers for. Light analysis is queued by the engine (`JobContext` follow-up) +after an import or a scan that indexed something; screens never queue it again. + +## 3. Data flow + +``` + card / folder ──► Core.Import (plan, sessions) ──► ImportService ─┐ + Uploader / client ──► POST /uploads, chunks ──► UploadService ────┤ hash verified + ▼ + ArchiveIngest: temp → fsync → rename into originals/, + sidecar (sequence.json, journalled) → index rows + │ + ┌────────────────────────────────────────────────────┼─────────────────────────┐ + ▼ ▼ ▼ + LightAnalyse (metadata) Thumbs / Proxies (thumbs.pack) events: sequenceChanged + DeepAnalyse (pixels, checkpoints) + │ + ▼ + Advice.Advisor → ProjectSettings (Auto values with reasons) → project.json + │ + ▼ + Render job: RenderPlan → RenderPipeline (FrameWindow, motion, deflicker…) → IVideoEncoderProvider + │ desktop: Media Foundation → managed; server: render node (GPU PC) + ▼ + output file (temp → rename) + renders row +``` + +The sidecars are the truth; the index is derived and can always be rebuilt (`ScanMode.Rebuild`, using the index +snapshot when fresh). Writers coordinate through lease files, so a desktop and a server may share an archive. + +## 4. Extension points + +| To add | Implement / register | +|---|---| +| An image format or decoder | `IImageDecoderProvider` (managed in `Core/Imaging/Decoders` or `Codecs`, WIC in `Core.Windows`); chained by `DecoderFactory` | +| A video encoder | `IVideoEncoderProvider` (`Core/Video/Managed`, `Core.Windows/MediaFoundation`); list it in the host's `ProcessingOptions.Encoders` | +| A background operation | a `JobKind`, an `IJobHandler` (in `Data/Archiving/Jobs` or `Data/Processing/Jobs`) returned by the service's `CreateJobHandlers`; the job engine, Jobs screen, admin and API pick it up | +| A server feature | a static `XxxEndpoints.Map(api)` in `Server/Api` with `.Requires(Permissions…)`, called from `ServerHost.ConfigurePipeline`; DTOs in `Titano.Protocol` with the JSON context | +| A server storage backend | `IArchiveIngest`, `IFrameAssetLocator` through the `ServerHost.Build` registration callback | +| A schema change | `Data/Migrations/{sqlite,postgres}/NNNN_topic.sql` (never edit an applied one) | +| An advisor rule | `Core/Advice` with a localised reason key in `Advisor` | +| A UI string | `i18n/en/.resx` + `i18n/it/.it.resx` (other languages via `i18n missing`/`import`) | +| An admin page | ES module in `Server/Admin/web/pages`, strings in the `Admin` area | +| A CLI command | `ICommand` in `Tools/Commands`, listed in `Tools/Program.cs` | + +## 5. Conventions - File-scoped namespaces, `sealed` by default, nullable on, warnings are errors. No `#pragma warning disable` except narrowly around interop with a reason. - No third-party packages, ever. If the BCL lacks it (CRC-32, Adler, JPEG, PNG decode…), write it. -- Parsers never throw on malformed input: they return partial results plus warnings. Every offset is - bounds-checked against the stream length; recursion and loops are capped. +- Never name a namespace `Archive` (it would shadow the entity): the archive code lives in `Archiving`. Inside + Titano.Core never write an unqualified `Math.`: use `System.Math` or `double.Max`. +- Parsers never throw on malformed input: they return partial results plus warnings. Every offset is bounds-checked + against the stream length; recursion and loops are capped. - Never load a whole RAW to read metadata: windowed reads through `Stream` + `Seek`. -- Hot loops: `Span`, `System.Numerics.Vector`/`Vector256` where it measurably pays, no LINQ. - Parallelise per row/tile with `Parallel.For` only when work per item is large. +- Hot loops: `Span`, `System.Numerics.Vector`/`Vector256` where it measurably pays, no LINQ. Parallelise per + row/tile with `Parallel.For` only when work per item is large. - Pixel math in linear light, `float`, Rec.709 primaries. Convert to sRGB/8-bit only at the edges. -- Every long operation takes a `CancellationToken` and reports progress through `IProgress`. -- Libraries use `ConfigureAwait(false)`. No `async void` except WPF event handlers. -- Logging through `Titano.Core.Diagnostics.Log` in Core; `ILogger` on the server. +- Every long operation takes a `CancellationToken` and reports progress through `IProgress` or the `JobContext`. +- Libraries use `ConfigureAwait(false)`. No `async void` except WPF event handlers. Heavy work and I/O never run on + the UI thread. +- Logging through `Titano.Core.Diagnostics.Log` in Core and Data; `ILogger` on the server. Anything that leaves the + machine (diagnostics bundles) passes through `SecretScrubber`. - Public types and non-obvious members get a one-line `///` summary. Comments explain *why*, not *what*. -- Disk writes that must survive crashes use `AtomicFile` (temp → fsync → rename). -- IDs are UUIDv7 (`Guid.CreateVersion7()`); timestamps UTC; capture times are camera wall-clock with an - optional offset. +- Disk writes that must survive crashes use `AtomicFile` (temp → fsync → rename); originals are never modified. +- IDs are UUIDv7 (`Guid.CreateVersion7()`); timestamps UTC; capture times are camera wall-clock with an optional + offset. +- The only OS actions the programs perform are those of BRIEF §8.6: open a URL and show a folder or file in Explorer + (`ShellActions` in the App), the format-volume dialog (`Core.Windows/Devices`). Downloaded updates (the setup, or + the portable zip for a portable copy) are shown in Explorer, never started. -## 4. Tests +## 6. Tests -- Framework: `Titano.Testing`. Test classes are `public sealed`; constructor may take `TestContext` - (temp directories, cancellation, log). Use `[WindowsOnly]` for OS-specific tests and - `[RequiresEnvironment("TITANO_TEST_PG")]` for PostgreSQL integration tests. +- Framework: `Titano.Testing`. Test classes are `public sealed`; constructor may take `TestContext` (temp + directories, cancellation, log). `[WindowsOnly]` for OS-specific tests, `[RequiresEnvironment("TITANO_TEST_PG")]` + for PostgreSQL integration tests. - Put tests under `tests/Titano..Tests//Tests.cs`, mirroring the source folder. -- Fixtures are synthetic and generated in code wherever possible; tiny binary fixtures may go in - `tests/fixtures/` (< 50 KB each). Larger CC0 samples are fetched by `Titano.Tools fixtures` into - `tests/fixtures/external/` (git-ignored) and tests depending on them skip when absent. +- `Titano.App.Tests` targets net10.0-windows and runs on Windows CI only: keep logic in plain classes. +- Fixtures are synthetic and generated in code wherever possible; tiny binary fixtures may go in `tests/fixtures/` + (< 50 KB each). CC0 RAW samples are fetched by `Titano.Tools fixtures` into `tests/fixtures/external/` (not + committed); tests depending on them skip when absent and CI shows a warning per missing sample. - Fuzz tests: truncate and corrupt valid inputs at many offsets; assert no exception escapes. +- Performance gates (`tests/Titano.Data.Tests/Perf`, `[Category("perf")]`, run only with `TITANO_PERF=1`): the + 500,000-photo library (Library open < 1 s on a new connection pool, filters < 200 ms; the OS cache is warm from + building it) and the 100,000-frame rebuild from sidecars (400 sequences of 250 real photos, every column compared, + < 120 s), each on SQLite and PostgreSQL. `.github/workflows/perf.yml` runs them weekly against PostgreSQL 17. +- `Titano.Tools.Tests` covers the tools whose output CI relies on (fixtures annotations and exit codes). -## 5. Localization +## 7. Localization -- Keys: `Area.Group.Name`; area = file name. Areas: Common, Shell, Library, Editor, Import, Archive, - Jobs, Server, Settings, Tooltips, Errors, Advisor, Admin, Uploader, Setup. -- `en` is the source (`i18n/en/.resx`), `it` is mandatory (`i18n/it/.it.resx`). +- Keys: `Area.Group.Name`; area = file name. Areas: About, Admin, Advisor, Archive, Common, Editor, Errors, Export, + Import, Jobs, Library, Server, Settings, Setup, Shell, Tooltips, Uploader. +- `en` is the source (`i18n/en/.resx`), `it` is mandatory (`i18n/it/.it.resx`); other languages are + machine-translated through `i18n missing` / `i18n import` with `i18n/GLOSSARY.md` and a per-language glossary. - Labels ≤ 30 chars, tooltips/errors/advisor reasons ≤ 200 chars (one or two sentences). - Plurals: `Key.one` / `Key.few` / `Key.many` / `Key.other`, resolved by `Loc.Plural("Key", n)`. -## 6. Build and checks +## 8. Build, checks and CI ``` dotnet build Titano.slnx -c Release @@ -85,4 +186,12 @@ dotnet run --project tests/Titano.Core.Tests -c Release -- --junit out/core.xml dotnet run --project src/Titano.Tools -- package-guard dotnet run --project src/Titano.Tools -- i18n check dotnet run --project src/Titano.Tools -- xaml-lint +dotnet format whitespace Titano.slnx --verify-no-changes ``` + +| Workflow | Trigger | Does | +|---|---|---| +| `ci.yml` | push to `main`, pull requests | Windows + Linux build and tests, guards, i18n, XAML lint, format, fixtures (warnings when missing), screenshots, PostgreSQL 16/17, Docker smoke test | +| `release.yml` | tag `v*` (or manual re-publish) | Tests, self-contained publish, optional signing, installers, portable and server zips, SHA256SUMS, release notes, multi-arch GHCR image, public releases repository update and GitHub release | +| `docker.yml` | nightly | `ghcr.io//titano-server:nightly` | +| `perf.yml` | weekly, manual | Performance gates (SQLite, PostgreSQL 17) with timings in the job summary | diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 73358d86..ff29bf56 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -1,17 +1,87 @@ # Changelog -All notable changes. Format: Keep a Changelog; versions follow SemVer; commits follow Conventional Commits. +All notable changes. Format: [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); versions follow SemVer; +commits follow Conventional Commits (release notes are generated from them by `Titano.Tools changelog`). ## [Unreleased] ### Added -- Repository foundation: solution, build rules (warnings as errors, zero-package guard), .NET 10 SDK pin. -- `Titano.Testing`: in-house test framework and runner with JUnit XML output and GitHub annotations. -- Localization runtime (`Loc`, CLDR plural rules, 38 shipped languages), `en` + `it` catalogs, `i18n check/export/missing/import`, translation glossary. -- Brand mark geometry, SDF rasteriser, PNG encoder, ICO writer and `make-icon` (program icons generated at build time). -- Core contracts: image buffers and decoder providers, video encoder providers, domain model, TIFF/IFD reader, sRGB helpers, atomic file writes, logging. -- `Titano.Ui` design system: DESIGN.md tokens (dark/light), 100+ stroke icons, styles for every standard control, custom chrome window with snap layouts, navigation rail, job bar, Auto/manual slider, chips, status glyphs, toasts, empty states. -- Titano desktop shell: rail, job bar, status strip, sections, Settings (language, theme) and About; `--capture` screenshot mode. -- Titano Server skeleton: configuration from environment/`server.json`, self-signed TLS with fingerprint, `/health`, `/api/v1/server/info`, `/api/v1/i18n/{culture}`, embedded admin panel (login, dashboard). + +#### Foundation +- Solution and build rules: warnings as errors, nullable, .NET 10 SDK pin, zero-package guard (build target and + `Titano.Tools package-guard`). +- `Titano.Testing`: in-house test framework and runner (theories, categories, timeouts, environment and Windows + gates, serial classes, parallel runs, JUnit XML, GitHub annotations). +- Localization runtime (`Loc`, CLDR plural rules with few/many forms, runtime culture switch, RTL), `en` + `it` + catalogs, machine translations with per-language glossaries, `i18n check/export/missing/import`. +- Brand mark geometry, SDF rasteriser, PNG encoder, ICO writer and `make-icon` (icons generated at build time). + +#### Engine (Titano.Core) +- Metadata: signature sniffing, TIFF/Exif/GPS/XMP/MakerNotes, JPEG segments, ISO-BMFF (HEIF, CR3), RAF, PNG, + WebP and RIFF parsers with fuzz-tested partial results; `MetadataBuilder` fallback chains; `ExifWriter`. +- Codecs: JPEG (baseline, progressive, lossless; libjpeg-exact integer IDCT), PNG, TIFF, linear DNG writer, GIF and + APNG encoders, ICO; native RAW development for DNG (opcodes, AHD demosaic, DNG colour), CR2, NEF, ARW, PEF, RAF. +- Imaging: planar linear-light buffers, decoder providers and decode tiers, separable resampler, frame window with + read-ahead, memory budget and float32 spill, `thumbs.pack`, thumbnail cache, proxy builder. +- Analysis and advisor: frame statistics, colour temperature, deflicker (global and regional), holy-grail step + redistribution, white-balance smoothing, light analysis with findings, streaming deep analysis with checkpoints; + `Advisor` recommendations with localised reasons, apply/optimise, sequence presets. +- Motion: FFT and phase correlation, pyramidal Lucas–Kanade flow, motion blur, nine-patch stabiliser, virtual + camera, frame interpolation, stacking and star trails. +- Render and export: render plan (constant, adaptive, interpolated, remapped timing), preparation pass, geometry, + pipeline, self-test suite (`Titano.Tools selftest`); preset resolution, encoder selection with hardware preference + and fallbacks, output naming. +- Video: streaming MP4 muxer (H.264/HEVC/AV1) with inspector, AVI-MJPEG with OpenDML indexes, NV12/P010 + conversion, level tables, managed encoder provider (MJPEG-AVI, image sequences, GIF, APNG). +- Archive format: layout and naming templates, sidecars, leases, index snapshot, scanner, verify, adopt, orphans, + rename plans; card import planning, sessions, hash-verified copy and verified erase; TPK1 installer payload. +- Diagnostics: `SecretScrubber` and `DiagnosticsArchive` for diagnostics bundles that never carry passwords, + tokens, keys or photos. + +#### Data (Titano.Data) +- SQLite binding (winsqlite3 / libsqlite3) and in-house PostgreSQL wire protocol v3 client (pool, prepared + statements, COPY, LISTEN, cancellation). +- Migrations, repositories and the `TitanoDatabase` facade; one persistent job engine with checkpoints, + pause/resume, priorities and crash recovery for client and server. +- Archive engine: create/adopt/open, incremental and full scans, rebuild from sidecars, ingest of uploads and card + imports, verify, thumbnails and proxies, maintenance, mass rename, job handlers. +- Analysis and render engine: light/deep analysis and render job handlers, render node client. + +#### Programs +- Titano desktop: shell with rail, job bar and toasts; Welcome, Library (virtualised grid and list, filters, sort, + hover scrubbing), Jobs, Server (trust-on-first-use sign-in, DPAPI token), Settings (general, archive, rendering + with encoder inventory and self-test, storage, server, updates, advanced) and About; `--capture` screenshots. +- Update check against the public releases repository and **Download**: the setup (the portable zip for a portable + copy) is fetched into `%TEMP%\Titano\updates`, verified against the release's `SHA256SUMS` and shown in Explorer; + an interrupted download resumes, *Cancel* stops it, and a transfer that stalls for 60 s fails. +- Diagnostics bundle (Settings › Advanced, About): environment, codec and encoder inventory, scrubbed settings, + recent failed jobs and logs. +- Titano Server: configuration from `server.json` and `TITANO_*`, TLS (auto, PEM, proxy), API v1 (auth, users, + sequences, frames, uploads, sync, jobs, render nodes, events over WebSocket, archive), admin panel (dashboard, + users, archive, jobs, settings, logs, about), audit log, LAN discovery, Windows service. +- Server diagnostics: `GET /api/v1/server/diagnostics` (ManageArchive, audited) and a *Diagnostics* button in admin › + Logs. +- Titano Uploader: tray program with resumable persisted queue, session grouping, watch folders, bandwidth limit, + verified-only source deletion. +- Titano Setup: one-screen installer, per-user or all-users, components, shortcuts, file types, upgrade in place, + silent mode, uninstaller that keeps user data unless asked. + +#### Distribution and CI - Docker image (multi-arch, PUID/PGID, health check), compose file with PostgreSQL 17, Unraid template. -- CI (Windows + Linux build/test, PostgreSQL 16/17, Docker smoke test, screenshots, Windows program artifacts), release and nightly image workflows. +- CI: Windows + Linux build and tests, PostgreSQL 16/17, Docker smoke test, screenshots branch, i18n, XAML lint, + format and package guards. +- Release workflow: tests, self-contained publish, optional Authenticode signing, installers, portable and server + zips, `SHA256SUMS`, release notes from Conventional Commits, multi-arch GHCR image, and the public releases + repository (README, EULA draft, SECURITY policy, issue forms, Unraid template, compose file, screenshots, `i18n/`). +- Performance gates (`perf.yml`, weekly): 500,000-photo library and 100,000-frame rebuild from sidecars (every + column compared), each on SQLite and PostgreSQL 17. +- `Titano.Tools.Tests`: the fixtures command's warning annotations and exit codes. + +### Fixed +- Release workflow: signing and the public-repository publish never ran (step conditions cannot read the step's own + secrets); the publish job lacked the .NET SDK for `make-icon`; re-publishing an existing tag failed; the portable + zip lacked `portable.txt`. +- CI fixtures step reported missing RAW samples as a silent pass; it now emits a warning per missing sample. +- Release workflow: the server image and its `:latest` tag were pushed before the Windows tests passed, and + publishing an older tag again moved `:latest` back; the image now follows the tests and `:latest` the newest + stable release. Stable release notes started at the last release candidate instead of the previous stable tag. diff --git a/docs/STATUS.md b/docs/STATUS.md index 8ae31a7c..63efda06 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -4,15 +4,15 @@ Phase plan: docs/BRIEF.md §22. Windows behaviour is verified on CI (`windows-la | Phase | State | |---|---| -| 0 Bootstrap | Done: solution, rules, Titano.Testing, zero-package guard, i18n (en, it; 36 cultures scaffolded), WPF shell, server skeleton, Docker, icons, CI. | -| 1 Metadata and imaging | Done: metadata parsers, managed codecs (JPEG, PNG, TIFF, GIF, APNG, ICO, linear DNG writer), WIC provider, colour/resampling. RAW/DNG decode pipeline in progress. | -| 2 Data layer and archive | Data layer done (SQLite binding, PostgreSQL wire client, migrations, repositories, job engine). Archive layout, sidecars, scan, rebuild, verify, duplicates, orphans, adopt: in progress. | -| 3 Library and Archive manager | Visual controls done (virtualised card grid, charts, filmstrip, preview, curve editor). Library, Jobs, Settings, Welcome, Server and About screens: in progress. Archive manager screen: next. | -| 4 Card import | Engine in progress with the archive workstream; screen next. | -| 5 Analysis advisor | In progress. | -| 6 Engine, encoding, editor | Video containers and encoders done (MP4, AVI, GIF/APNG, Media Foundation H.264/HEVC/AV1); render pipeline in progress; editor screen next. | -| 7 Server, sync, uploader | Uploader done. Full server (API, auth, uploads, sync, jobs, render nodes, events, admin panel, Windows service) in progress. | -| 8 Release readiness | Installer, release/docker workflows and Unraid template in place; translations, accessibility and performance passes pending. | +| 0 Bootstrap | Done: solution, rules, Titano.Testing, zero-package guard, i18n, WPF shell, server skeleton, Docker, icons, CI. | +| 1 Metadata and imaging | Done: metadata parsers, managed codecs, native RAW development (DNG, CR2, NEF, ARW, PEF, RAF), WIC provider and codec inventory, decode tiers, thumbnails and proxies, `diagnose`. Real-camera fixtures wait for verified raw.pixls.us URLs (CI warns per missing sample). | +| 2 Data layer and archive | Done: SQLite binding, PostgreSQL wire client, migrations, repositories, job engine, archive layout, sidecars, scan, rebuild, verify, duplicates, orphans, adopt, mass rename. Gate measured: a 100,000-frame archive (400 sequences of 250 photos) rebuilds from sidecars into an index identical in every column in 1.8 s on SQLite and 4.7 s on PostgreSQL (budget 120 s). | +| 3 Library and Archive manager | Library, Jobs, Settings, Welcome, Server and About screens done; Archive manager screen in progress. Gate measured on 500,000 photos: Library open 259 ms on SQLite and 181 ms on PostgreSQL on a new connection pool (warm OS cache; budget 1 s); every filter, search, sort and next page ≤ 6.4 ms (budget 200 ms). | +| 4 Card import | Engine done (plan, sessions, hash-verified copy, verified erase, import jobs); screen in progress. | +| 5 Analysis advisor | Engine done (light and deep analysis, advisor, presets, analysis jobs); editor integration in progress. | +| 6 Engine, encoding, editor | Render pipeline, MP4/AVI/GIF/APNG/image sequences, Media Foundation H.264/HEVC/AV1 done; sequence editor in progress. | +| 7 Server, sync, uploader | Server (API, auth, uploads, jobs, render nodes, events, admin panel, Windows service) and Uploader done; client sync in progress. | +| 8 Release readiness | Release pipeline end to end (installers, portable and server zips, SHA256SUMS, release notes, optional signing, multi-arch GHCR image, public releases repository content), update check with verified download, scrubbed diagnostics bundles (desktop and server), performance gates, machine translations. Pending: remaining languages, RTL and accessibility passes, a tagged pre-release published from CI, install/upgrade/uninstall test on Windows, Unraid template validation on a real server. | | 9 Monetization | Not started: requires explicit approval (§22). | ## How to try it @@ -23,4 +23,18 @@ dotnet run --project src/Titano.Server # https://localhost:8443/admin src/Titano.App/bin/Release/net10.0-windows/Titano.exe # Windows src/Titano.Uploader/bin/Release/net10.0-windows/Titano.Uploader.exe # Windows docker compose -f deploy/docker/docker-compose.yml up -d # server + PostgreSQL 17 +TITANO_PERF=1 dotnet run --project tests/Titano.Data.Tests -c Release -- --filter category:perf --verbose # performance gates ``` + +- Diagnostics: Settings › Advanced › Diagnostics › *Export bundle* (desktop) or admin panel › Logs › *Diagnostics* (server, + `GET /api/v1/server/diagnostics`). Open the zip: logs, reports, settings and failed jobs, no passwords or tokens. +- Update download: About › *Check for updates*, then *Download* when a newer release exists; the verified setup (the + portable zip in a portable copy) appears in Explorer. *Cancel* stops it; the next *Download* resumes. + +## Next steps (Phase 8 gate) + +1. Create the public repository (`/titano-releases`), add the `RELEASES_TOKEN` secret, push a `v0.x.y-rc.1` + tag and check the release, the public repository content and the GHCR image (set it public once). +2. On Windows: install, upgrade over the previous version, uninstall (with and without user data), silent mode. +3. Unraid: add the template repository, install with the official PostgreSQL template, reach the WebUI. +4. Remaining languages, RTL pass (`ar`, `he`, `fa`, `ur`), accessibility pass. diff --git a/i18n/ar/Tooltips.ar.resx b/i18n/ar/Tooltips.ar.resx index e17cf9a4..15e4360c 100644 --- a/i18n/ar/Tooltips.ar.resx +++ b/i18n/ar/Tooltips.ar.resx @@ -5,8 +5,6 @@ System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 الاستعلام من صفحة الإصدارات العامة عن إصدار أحدث · بضع ثوانٍ - ضغط السجلات وتقرير عن البيئة في ملف ZIP داخل مجلد تختاره؛ ولا تُضمَّن الإعدادات وكلمات المرور - فتح صفحة الإصدار في المستعرض فتح الترخيص في المستعرض فتح المجلد الذي يضم قاعدة البيانات والإعدادات والسجلات فتح صفحة الإصدارات العامة في المستعرض @@ -139,7 +137,6 @@ حذف الإطارات المُفرَغة والصور المصغرة المخزنة مؤقتًا؛ مع طلب التأكيد أولًا قاعدة البيانات والإعدادات والسجلات وذاكرات التخزين المؤقت لهذا الكمبيوتر الخادم الذي يتصل به Titano عند البدء؛ تغييره يسجّل الخروج · Enter للتطبيق، Esc للتراجع - ضغط السجلات وتقرير عن البيئة في ملف ZIP داخل مجلد تختاره حفظ كل الإعدادات بتنسيق JSON، دون رمز الجلسة اسم ملف كل إطار، مثل {date}_{time}_{n:0000}؛ ويُضاف الامتداد · Enter للتطبيق، Esc للتراجع مجلدات الأرشيف، مثل {year}/{date} {camera}؛ الشرطة المائلة تبدأ مجلدًا فرعيًا · Enter للتطبيق، Esc للتراجع diff --git a/i18n/bg/Tooltips.bg.resx b/i18n/bg/Tooltips.bg.resx index 92f921b8..bdbbbad0 100644 --- a/i18n/bg/Tooltips.bg.resx +++ b/i18n/bg/Tooltips.bg.resx @@ -5,8 +5,6 @@ System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 Проверява на публичната страница с издания за по-нова версия · няколко секунди - Архивира в ZIP журналите и отчет за средата в избрана от вас папка; настройките и паролите не се включват - Отваря страницата на изданието в браузъра Отваря лиценза в браузъра Отваря папката с базата данни, настройките и журналите Отваря публичната страница с издания в браузъра @@ -135,7 +133,6 @@ Изтрива изместените кадри и кешираните миниатюри; първо пита База данни, настройки, журнали и кешове на този компютър Сървър, към който Titano се свързва при стартиране; промяната води до излизане · Enter прилага, Esc връща - Архивира в ZIP журналите и отчет за средата в избрана от вас папка Записва всички настройки като JSON, без маркера за сесията Име на файла на всеки кадър, например {date}_{time}_{n:0000}; разширението се добавя · Enter прилага, Esc връща Папки на архива, например {year}/{date} {camera}; наклонената черта започва подпапка · Enter прилага, Esc връща diff --git a/i18n/cs/Tooltips.cs.resx b/i18n/cs/Tooltips.cs.resx index 688a1f35..815df36e 100644 --- a/i18n/cs/Tooltips.cs.resx +++ b/i18n/cs/Tooltips.cs.resx @@ -5,8 +5,6 @@ System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 Zjistí na veřejné stránce vydání, zda je k dispozici novější verze · několik sekund - Zabalí protokoly a zprávu o prostředí do souboru ZIP ve zvolené složce; nastavení a hesla nejsou zahrnuta - Otevře stránku vydání v prohlížeči Otevře licenci v prohlížeči Otevře složku s databází, nastavením a protokoly Otevře veřejnou stránku vydání v prohlížeči @@ -137,7 +135,6 @@ Odstraní odložené snímky a miniatury v mezipaměti; nejprve se zeptá Databáze, nastavení, protokoly a mezipaměti tohoto počítače Server, ke kterému se Titano připojí při spuštění; změna vás odhlásí · Enter použije, Esc vrátí zpět - Zabalí protokoly a zprávu o prostředí do souboru ZIP ve zvolené složce Uloží všechna nastavení jako JSON, bez tokenu relace Název souboru každého snímku, například {date}_{time}_{n:0000}; přípona se přidá · Enter použije, Esc vrátí zpět Složky archivu, například {year}/{date} {camera}; lomítko zahájí podsložku · Enter použije, Esc vrátí zpět diff --git a/i18n/da/Tooltips.da.resx b/i18n/da/Tooltips.da.resx index 4d3be04a..46442f2b 100644 --- a/i18n/da/Tooltips.da.resx +++ b/i18n/da/Tooltips.da.resx @@ -5,8 +5,6 @@ System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 Spørg den offentlige udgivelsesside efter en nyere version · et par sekunder - Pak logfilerne og en miljørapport som ZIP i en mappe, du vælger; indstillinger og adgangskoder medtages ikke - Åbn udgivelsessiden i browseren Åbn licensen i browseren Åbn mappen med database, indstillinger og logge Åbn den offentlige udgivelsesside i browseren @@ -135,7 +133,6 @@ Slet udlagte billeder og cachelagrede miniaturer; spørger først Database, indstillinger, logge og cacher på denne pc Server, som Titano opretter forbindelse til ved start; en ændring logger dig af · Enter anvender, Esc fortryder - Pak logfilerne og en miljørapport som ZIP i en mappe, du vælger Gem alle indstillinger som JSON uden sessionstokenet Filnavn for hvert billede, f.eks. {date}_{time}_{n:0000}; filtypenavnet tilføjes · Enter anvender, Esc fortryder Arkivmapper, f.eks. {year}/{date} {camera}; en skråstreg starter en undermappe · Enter anvender, Esc fortryder diff --git a/i18n/de/Tooltips.de.resx b/i18n/de/Tooltips.de.resx index 46e24161..764b5e00 100644 --- a/i18n/de/Tooltips.de.resx +++ b/i18n/de/Tooltips.de.resx @@ -5,8 +5,6 @@ System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 Auf der öffentlichen Release-Seite nach einer neueren Version suchen · wenige Sekunden - Protokolle und einen Umgebungsbericht als ZIP in einen Ordner Ihrer Wahl packen; Einstellungen und Kennwörter sind nicht enthalten - Release-Seite im Browser öffnen Lizenz im Browser öffnen Ordner mit Datenbank, Einstellungen und Protokollen öffnen Öffentliche Release-Seite im Browser öffnen @@ -135,7 +133,6 @@ Ausgelagerte Frames und zwischengespeicherte Miniaturansichten löschen; fragt vorher nach Datenbank, Einstellungen, Protokolle und Caches dieses PCs Server, mit dem sich Titano beim Start verbindet; eine Änderung meldet Sie ab · Enter übernimmt, Esc macht rückgängig - Protokolle und einen Umgebungsbericht als ZIP in einen Ordner Ihrer Wahl packen Alle Einstellungen als JSON speichern, ohne das Sitzungstoken Dateiname jedes Frames, zum Beispiel {date}_{time}_{n:0000}; die Erweiterung wird angehängt · Enter übernimmt, Esc macht rückgängig Archivordner, zum Beispiel {year}/{date} {camera}; ein Schrägstrich beginnt einen Unterordner · Enter übernimmt, Esc macht rückgängig diff --git a/i18n/el/Tooltips.el.resx b/i18n/el/Tooltips.el.resx index 2450c149..ad292da1 100644 --- a/i18n/el/Tooltips.el.resx +++ b/i18n/el/Tooltips.el.resx @@ -5,8 +5,6 @@ System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 Αναζήτηση νεότερης έκδοσης στη δημόσια σελίδα εκδόσεων · λίγα δευτερόλεπτα - Συμπίεση των αρχείων καταγραφής και μιας αναφοράς περιβάλλοντος σε ZIP, σε φάκελο της επιλογής σας. Οι ρυθμίσεις και οι κωδικοί πρόσβασης δεν περιλαμβάνονται - Άνοιγμα της σελίδας της έκδοσης στο πρόγραμμα περιήγησης Άνοιγμα της άδειας χρήσης στο πρόγραμμα περιήγησης Άνοιγμα του φακέλου με τη βάση δεδομένων, τις ρυθμίσεις και τα αρχεία καταγραφής Άνοιγμα της δημόσιας σελίδας εκδόσεων στο πρόγραμμα περιήγησης @@ -135,7 +133,6 @@ Διαγραφή των καρέ που μεταφέρθηκαν στον δίσκο και των μικρογραφιών της κρυφής μνήμης. Ζητείται πρώτα επιβεβαίωση Βάση δεδομένων, ρυθμίσεις, αρχεία καταγραφής και κρυφή μνήμη αυτού του υπολογιστή Ο διακομιστής στον οποίο συνδέεται το Titano κατά την εκκίνηση. Η αλλαγή του προκαλεί έξοδο · Enter για εφαρμογή, Esc για αναίρεση - Συμπίεση των αρχείων καταγραφής και μιας αναφοράς περιβάλλοντος σε ZIP, σε φάκελο της επιλογής σας Αποθήκευση όλων των ρυθμίσεων ως JSON, χωρίς το διακριτικό περιόδου σύνδεσης Όνομα αρχείου κάθε καρέ, για παράδειγμα {date}_{time}_{n:0000}. Η επέκταση προστίθεται αυτόματα · Enter για εφαρμογή, Esc για αναίρεση Φάκελοι της αρχειοθήκης, για παράδειγμα {year}/{date} {camera}. Μια κάθετος ξεκινά υποφάκελο · Enter για εφαρμογή, Esc για αναίρεση diff --git a/i18n/en/About.resx b/i18n/en/About.resx index ce8aea99..37466cd9 100644 --- a/i18n/en/About.resx +++ b/i18n/en/About.resx @@ -19,10 +19,16 @@ None Translation Titano {0} available + Cancel Check for updates Checking… Up to date Download + Download failed + Downloading {0:P0} Check failed + Download not verified + Titano {0} downloaded + Show file Updates diff --git a/i18n/en/Admin.resx b/i18n/en/Admin.resx index 0933d7a3..d2a47e16 100644 --- a/i18n/en/Admin.resx +++ b/i18n/en/Admin.resx @@ -175,11 +175,14 @@ Sequence created Sequence deleted Sequence edited + Diagnostics exported Server settings User created User deleted User changed Details + Diagnostics + Download a zip with logs, system report, settings and recent failed jobs; passwords and tokens are left out Download Save this log file Nothing recorded yet diff --git a/i18n/en/Tooltips.resx b/i18n/en/Tooltips.resx index 7ca6cbe4..6ece7aea 100644 --- a/i18n/en/Tooltips.resx +++ b/i18n/en/Tooltips.resx @@ -4,13 +4,18 @@ 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Stop the download; Download resumes it later from where it stopped Ask the public releases page for a newer version · a few seconds - Zip the logs and an environment report into a folder you choose; settings and passwords are not included - Open the release page in the browser + Zip the logs, a system and codec report, settings and recent failed jobs into a folder you choose; passwords, tokens and photos are left out + Download the setup, check it against the release's SHA-256 list and show it in Explorer · {0} + Open the page of this release in the browser + Download the portable zip, check it against the release's SHA-256 list and show it in Explorer · {0} Open the licence in the browser Open the folder with database, settings and logs Open the public releases page in the browser Every language but English is machine-translated; propose a better wording on the public issue tracker + Show the verified zip in Explorer; close Titano and unpack it over this folder to upgrade. The data folder is kept + Show the verified setup in Explorer; close Titano and run it to upgrade. Archive and settings are kept Titano uses no third-party code: everything beyond .NET and Windows is written in-house Dismiss Open the folder with the log files @@ -135,7 +140,7 @@ Delete spilled frames and cached thumbnails; asks first Database, settings, logs and caches of this PC Server Titano connects to at start; changing it signs out · Enter applies, Esc reverts - Zip the logs and an environment report into a folder you choose + Zip the logs, a system and codec report, settings and recent failed jobs into a folder you choose; passwords, tokens and photos are left out Save every setting as JSON, without the session token File name of each frame, for example {date}_{time}_{n:0000}; the extension is added · Enter applies, Esc reverts Archive folders, for example {year}/{date} {camera}; a slash starts a subfolder · Enter applies, Esc reverts diff --git a/i18n/es/Tooltips.es.resx b/i18n/es/Tooltips.es.resx index 807e5d05..725b7a2a 100644 --- a/i18n/es/Tooltips.es.resx +++ b/i18n/es/Tooltips.es.resx @@ -5,8 +5,6 @@ System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 Consulta la página pública de versiones por si hay una más reciente · unos segundos - Comprime los registros y un informe del entorno en una carpeta que elijas; no incluye la configuración ni las contraseñas - Abre la página de la versión en el navegador Abre la licencia en el navegador Abre la carpeta con la base de datos, la configuración y los registros Abre la página pública de versiones en el navegador @@ -135,7 +133,6 @@ Elimina los fotogramas volcados y las miniaturas en caché; pide confirmación antes Base de datos, configuración, registros y cachés de este equipo Servidor al que se conecta Titano al iniciar; si lo cambias, se cierra la sesión · Enter aplica, Esc revierte - Comprime los registros y un informe del entorno en una carpeta que elijas Guarda todos los ajustes como JSON, sin el token de sesión Nombre de archivo de cada fotograma, por ejemplo {date}_{time}_{n:0000}; la extensión se añade sola · Enter aplica, Esc revierte Carpetas de la fototeca, por ejemplo {year}/{date} {camera}; una barra inicia una subcarpeta · Enter aplica, Esc revierte diff --git a/i18n/et/Tooltips.et.resx b/i18n/et/Tooltips.et.resx index d6aaa068..79098c4b 100644 --- a/i18n/et/Tooltips.et.resx +++ b/i18n/et/Tooltips.et.resx @@ -5,8 +5,6 @@ System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 Kontrollige avalikult väljalasete lehelt, kas on uuem versioon · mõni sekund - Pakkige logid ja keskkonnaaruanne ZIP-faili teie valitud kausta; sätteid ja paroole ei lisata - Avage väljalaske leht brauseris Avage litsents brauseris Avage andmebaasi, sätete ja logidega kaust Avage avalik väljalasete leht brauseris @@ -135,7 +133,6 @@ Kustutage kettale tõstetud kaadrid ja vahemällu salvestatud pisipildid; küsitakse eelnevalt kinnitust Selle arvuti andmebaas, sätted, logid ja vahemälud Server, millega Titano käivitumisel ühendub; muutmine logib välja · Enter rakendab, Esc taastab - Pakkige logid ja keskkonnaaruanne ZIP-faili teie valitud kausta Salvestage kõik sätted JSON-failina, ilma seansiloata Iga kaadri failinimi, näiteks {date}_{time}_{n:0000}; laiend lisatakse · Enter rakendab, Esc taastab Arhiivi kaustad, näiteks {year}/{date} {camera}; kaldkriips alustab alamkausta · Enter rakendab, Esc taastab diff --git a/i18n/fi/Tooltips.fi.resx b/i18n/fi/Tooltips.fi.resx index 709ea9de..f76e3842 100644 --- a/i18n/fi/Tooltips.fi.resx +++ b/i18n/fi/Tooltips.fi.resx @@ -5,8 +5,6 @@ System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 Kysy julkisten julkaisujen sivulta, onko uudempaa versiota · muutama sekunti - Pakkaa lokit ja ympäristöraportti ZIP-tiedostoon valitsemaasi kansioon; asetuksia ja salasanoja ei sisällytetä - Avaa julkaisusivu selaimessa Avaa lisenssi selaimessa Avaa kansio, jossa ovat tietokanta, asetukset ja lokit Avaa julkisten julkaisujen sivu selaimessa @@ -135,7 +133,6 @@ Poista levylle siirretyt kuvat ja välimuistissa olevat pikkukuvat; kysyy ensin Tämän tietokoneen tietokanta, asetukset, lokit ja välimuistit Palvelin, johon Titano yhdistää käynnistyessään; vaihtaminen kirjaa ulos · Enter ottaa käyttöön, Esc palauttaa - Pakkaa lokit ja ympäristöraportti ZIP-tiedostoon valitsemaasi kansioon Tallenna kaikki asetukset JSON-muodossa ilman istuntotunnusta Kunkin kuvan tiedostonimi, esimerkiksi {date}_{time}_{n:0000}; tiedostotunniste lisätään · Enter ottaa käyttöön, Esc palauttaa Arkiston kansiot, esimerkiksi {year}/{date} {camera}; kauttaviiva aloittaa alikansion · Enter ottaa käyttöön, Esc palauttaa diff --git a/i18n/fr/Tooltips.fr.resx b/i18n/fr/Tooltips.fr.resx index 7b8a4b75..461f6ee1 100644 --- a/i18n/fr/Tooltips.fr.resx +++ b/i18n/fr/Tooltips.fr.resx @@ -5,8 +5,6 @@ System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 Interroger la page publique des versions pour trouver une version plus récente · quelques secondes - Compresser les journaux et un rapport d'environnement dans un dossier de votre choix ; les paramètres et les mots de passe ne sont pas inclus - Ouvrir la page de la version dans le navigateur Ouvrir la licence dans le navigateur Ouvrir le dossier contenant la base de données, les paramètres et les journaux Ouvrir la page publique des versions dans le navigateur @@ -135,7 +133,6 @@ Supprimer les images en débordement et les miniatures en cache ; demande confirmation Base de données, paramètres, journaux et caches de ce PC Serveur auquel Titano se connecte au démarrage ; le modifier ferme la session · Enter pour appliquer, Esc pour rétablir - Compresser les journaux et un rapport d'environnement dans un dossier de votre choix Enregistrer tous les paramètres au format JSON, sans le jeton de session Nom de fichier de chaque image, par exemple {date}_{time}_{n:0000} ; l'extension est ajoutée · Enter pour appliquer, Esc pour rétablir Dossiers de l'archive, par exemple {year}/{date} {camera} ; une barre oblique crée un sous-dossier · Enter pour appliquer, Esc pour rétablir diff --git a/i18n/he/Tooltips.he.resx b/i18n/he/Tooltips.he.resx index aa81c258..4e9de151 100644 --- a/i18n/he/Tooltips.he.resx +++ b/i18n/he/Tooltips.he.resx @@ -5,8 +5,6 @@ System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 בדיקה בדף הגרסאות הציבורי אם יש גרסה חדשה יותר · כמה שניות - דחיסת היומנים ודוח סביבה לקובץ ZIP בתיקייה לבחירתך; הגדרות וסיסמאות אינן נכללות - פתיחת דף הגרסה בדפדפן פתיחת הרישיון בדפדפן פתיחת התיקייה עם מסד הנתונים, ההגדרות והיומנים פתיחת דף הגרסאות הציבורי בדפדפן @@ -137,7 +135,6 @@ מחיקת פריימים שנשפכו לדיסק ותמונות ממוזערות שבמטמון; מבקש אישור תחילה מסד הנתונים, ההגדרות, היומנים והמטמונים של המחשב הזה השרת ש-Titano מתחבר אליו בהפעלה; שינוי שלו מוציא מהחשבון · Enter מחיל, Esc מבטל - דחיסת היומנים ודוח סביבה לקובץ ZIP בתיקייה לבחירתך שמירת כל ההגדרות כ-JSON, ללא אסימון הסשן שם הקובץ של כל פריים, לדוגמה {date}_{time}_{n:0000}; הסיומת מתווספת · Enter מחיל, Esc מבטל תיקיות הארכיון, לדוגמה {year}/{date} {camera}; לוכסן פותח תת-תיקייה · Enter מחיל, Esc מבטל diff --git a/i18n/hi/Tooltips.hi.resx b/i18n/hi/Tooltips.hi.resx index 427932cd..b00abe61 100644 --- a/i18n/hi/Tooltips.hi.resx +++ b/i18n/hi/Tooltips.hi.resx @@ -5,8 +5,6 @@ System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 नए संस्करण के लिए सार्वजनिक रिलीज़ पेज से पूछें · कुछ सेकंड - लॉग और परिवेश रिपोर्ट को आपके चुने फ़ोल्डर में ज़िप करें; सेटिंग्स और पासवर्ड शामिल नहीं होते - रिलीज़ पेज ब्राउज़र में खोलें लाइसेंस ब्राउज़र में खोलें डेटाबेस, सेटिंग्स और लॉग वाला फ़ोल्डर खोलें सार्वजनिक रिलीज़ पेज ब्राउज़र में खोलें @@ -135,7 +133,6 @@ डिस्क पर उतारे गए फ़्रेम और कैश किए गए थंबनेल हटाएँ; पहले पूछता है इस PC का डेटाबेस, सेटिंग्स, लॉग और कैश वह सर्वर जिससे Titano शुरू होने पर कनेक्ट होता है; इसे बदलने पर साइन आउट हो जाता है · Enter से लागू, Esc से पूर्ववत - लॉग और परिवेश रिपोर्ट को आपके चुने फ़ोल्डर में ज़िप करें सत्र टोकन के बिना सभी सेटिंग्स JSON के रूप में सहेजें हर फ़्रेम का फ़ाइल नाम, उदाहरण के लिए {date}_{time}_{n:0000}; एक्सटेंशन जोड़ दिया जाता है · Enter से लागू, Esc से पूर्ववत संग्रह फ़ोल्डर, उदाहरण के लिए {year}/{date} {camera}; स्लैश से उप-फ़ोल्डर शुरू होता है · Enter से लागू, Esc से पूर्ववत diff --git a/i18n/hr/Tooltips.hr.resx b/i18n/hr/Tooltips.hr.resx index 3780c1db..d1bd0cc9 100644 --- a/i18n/hr/Tooltips.hr.resx +++ b/i18n/hr/Tooltips.hr.resx @@ -5,8 +5,6 @@ System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 Provjerava na javnoj stranici izdanja postoji li novija verzija · nekoliko sekundi - Pakira zapisnike i izvješće o okruženju u ZIP datoteku u mapi po vašem izboru; postavke i lozinke nisu uključene - Otvara stranicu izdanja u pregledniku Otvara licencu u pregledniku Otvara mapu s bazom podataka, postavkama i zapisnicima Otvara javnu stranicu izdanja u pregledniku @@ -137,7 +135,6 @@ Briše odložene kadrove i minijature iz predmemorije; prije toga traži potvrdu Baza podataka, postavke, zapisnici i predmemorije ovog računala Poslužitelj s kojim se Titano povezuje pri pokretanju; promjena vas odjavljuje · Enter primjenjuje, Esc vraća - Pakira zapisnike i izvješće o okruženju u ZIP datoteku u mapi po vašem izboru Sprema sve postavke kao JSON, bez tokena sesije Naziv datoteke svakog kadra, npr. {date}_{time}_{n:0000}; nastavak se dodaje · Enter primjenjuje, Esc vraća Mape arhive, npr. {year}/{date} {camera}; kosa crta započinje podmapu · Enter primjenjuje, Esc vraća diff --git a/i18n/hu/Tooltips.hu.resx b/i18n/hu/Tooltips.hu.resx index 56293848..feb01f28 100644 --- a/i18n/hu/Tooltips.hu.resx +++ b/i18n/hu/Tooltips.hu.resx @@ -5,8 +5,6 @@ System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 Újabb verziót keres a nyilvános kiadási oldalon · néhány másodperc - A naplókat és egy környezeti jelentést ZIP-fájlba tömöríti egy választott mappába; beállításokat és jelszavakat nem tartalmaz - Megnyitja a kiadás oldalát a böngészőben Megnyitja a licencet a böngészőben Megnyitja az adatbázist, a beállításokat és a naplókat tartalmazó mappát Megnyitja a nyilvános kiadási oldalt a böngészőben @@ -135,7 +133,6 @@ Törli a lemezre kiírt képkockákat és a gyorsítótárazott miniatűröket; előbb megerősítést kér Ennek a számítógépnek az adatbázisa, beállításai, naplói és gyorsítótárai A szerver, amelyhez a Titano indításkor csatlakozik; módosítása kijelentkezéssel jár · Enter: alkalmaz, Esc: visszavon - A naplókat és egy környezeti jelentést ZIP-fájlba tömöríti egy választott mappába Minden beállítást JSON-fájlba ment, a munkamenet-token nélkül Az egyes képkockák fájlneve, például {date}_{time}_{n:0000}; a kiterjesztés automatikusan hozzáadódik · Enter: alkalmaz, Esc: visszavon Az archívum mappái, például {year}/{date} {camera}; a perjel almappát kezd · Enter: alkalmaz, Esc: visszavon diff --git a/i18n/id/Tooltips.id.resx b/i18n/id/Tooltips.id.resx index c770b19a..bccdd14c 100644 --- a/i18n/id/Tooltips.id.resx +++ b/i18n/id/Tooltips.id.resx @@ -5,8 +5,6 @@ System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 Periksa versi yang lebih baru di halaman rilis publik · beberapa detik - Kemas log dan laporan lingkungan sistem ke dalam ZIP di folder pilihan Anda; pengaturan dan kata sandi tidak disertakan - Buka halaman rilis di browser Buka lisensi di browser Buka folder berisi basis data, pengaturan, dan log Buka halaman rilis publik di browser @@ -135,7 +133,6 @@ Hapus bingkai limpahan dan gambar mini dalam cache; meminta konfirmasi terlebih dahulu Basis data, pengaturan, log, dan cache PC ini Server yang disambungkan Titano saat mulai; mengubahnya akan membuat Anda keluar · Enter menerapkan, Esc membatalkan - Kemas log dan laporan lingkungan sistem ke dalam ZIP di folder pilihan Anda Simpan semua pengaturan sebagai JSON, tanpa token sesi Nama file setiap bingkai, misalnya {date}_{time}_{n:0000}; ekstensi ditambahkan otomatis · Enter menerapkan, Esc membatalkan Folder arsip, misalnya {year}/{date} {camera}; garis miring memulai subfolder · Enter menerapkan, Esc membatalkan diff --git a/i18n/it/About.it.resx b/i18n/it/About.it.resx index 2370ca1e..c290af5d 100644 --- a/i18n/it/About.it.resx +++ b/i18n/it/About.it.resx @@ -19,10 +19,16 @@ Nessuno Traduzione Titano {0} disponibile + Annulla Cerca aggiornamenti Verifica in corso… Aggiornato Scarica + Download non riuscito + Download in corso {0:P0} Verifica non riuscita + Download non verificato + Titano {0} scaricato + Mostra file Aggiornamenti diff --git a/i18n/it/Admin.it.resx b/i18n/it/Admin.it.resx index e1bdb0f1..45da50d6 100644 --- a/i18n/it/Admin.it.resx +++ b/i18n/it/Admin.it.resx @@ -175,11 +175,14 @@ Sequenza creata Sequenza eliminata Sequenza modificata + Diagnostica esportata Impostazioni server Utente creato Utente eliminato Utente modificato Dettagli + Diagnostica + Scarica uno zip con log, rapporto di sistema, impostazioni e attività fallite di recente; password e token restano fuori Scarica Salva questo file di log Ancora nessuna registrazione diff --git a/i18n/it/Tooltips.it.resx b/i18n/it/Tooltips.it.resx index c81ad08f..4246176c 100644 --- a/i18n/it/Tooltips.it.resx +++ b/i18n/it/Tooltips.it.resx @@ -4,13 +4,18 @@ 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Interrompe il download; Scarica lo riprende in seguito dal punto in cui si è fermato Chiede alla pagina pubblica delle versioni se ne esiste una più recente · pochi secondi - Comprime i log e un rapporto sull'ambiente in una cartella a tua scelta; impostazioni e password non sono incluse - Apre la pagina della versione nel browser + Comprime log, rapporto su sistema e codec, impostazioni e attività fallite di recente in una cartella a tua scelta; password, token e foto restano fuori + Scarica l'installer, lo confronta con l'elenco SHA-256 della versione e lo mostra in Esplora file · {0} + Apre la pagina di questa versione nel browser + Scarica lo zip portatile, lo confronta con l'elenco SHA-256 della versione e lo mostra in Esplora file · {0} Apre la licenza nel browser Apri la cartella con database, impostazioni e log Apri la pagina pubblica delle versioni nel browser Tutte le lingue tranne l'inglese sono tradotte automaticamente; proponi una formulazione migliore nel tracker pubblico + Mostra in Esplora file lo zip verificato; chiudi Titano ed estrailo sopra questa cartella per aggiornare. La cartella dei dati resta invariata + Mostra in Esplora file l'installer verificato; chiudi Titano ed eseguilo per aggiornare. Archivio e impostazioni restano invariati Titano non usa codice di terze parti: tutto ciò che va oltre .NET e Windows è scritto internamente Chiudi Apri la cartella dei file di log @@ -135,7 +140,7 @@ Elimina fotogrammi temporanei e miniature in cache; prima chiede conferma Database, impostazioni, log e cache di questo PC Server a cui Titano si connette all'avvio; cambiarlo chiude l'accesso · Invio applica, Esc annulla - Comprime i log e un rapporto sull'ambiente in una cartella a tua scelta + Comprime log, rapporto su sistema e codec, impostazioni e attività fallite di recente in una cartella a tua scelta; password, token e foto restano fuori Salva tutte le impostazioni in JSON, senza il token di sessione Nome del file di ogni fotogramma, ad esempio {date}_{time}_{n:0000}; l'estensione viene aggiunta · Invio applica, Esc annulla Cartelle dell'archivio, ad esempio {year}/{date} {camera}; la barra crea una sottocartella · Invio applica, Esc annulla diff --git a/i18n/ja/Tooltips.ja.resx b/i18n/ja/Tooltips.ja.resx index 3a191e64..a02cdba6 100644 --- a/i18n/ja/Tooltips.ja.resx +++ b/i18n/ja/Tooltips.ja.resx @@ -5,8 +5,6 @@ System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 公開リリースページで新しいバージョンを確認します · 数秒 - ログと環境レポートを ZIP にまとめ、選択したフォルダーに保存します。設定とパスワードは含まれません。 - ブラウザーでリリースページを開きます。 ブラウザーでライセンスを開きます。 データベース、設定、ログがあるフォルダーを開きます。 ブラウザーで公開リリースページを開きます。 @@ -135,7 +133,6 @@ 一時退避したフレームとキャッシュされたサムネイルを削除します。実行前に確認します。 この PC のデータベース、設定、ログ、キャッシュ Titano が起動時に接続するサーバーです。変更するとサインアウトします · Enter で適用、Esc で元に戻す - ログと環境レポートを ZIP にまとめ、選択したフォルダーに保存します。 セッショントークンを除くすべての設定を JSON として保存します。 各フレームのファイル名です。例: {date}_{time}_{n:0000}。拡張子は自動で付きます · Enter で適用、Esc で元に戻す アーカイブのフォルダーです。例: {year}/{date} {camera}。スラッシュでサブフォルダーになります · Enter で適用、Esc で元に戻す diff --git a/i18n/ko/Tooltips.ko.resx b/i18n/ko/Tooltips.ko.resx index 70eb6ca7..92eaf41e 100644 --- a/i18n/ko/Tooltips.ko.resx +++ b/i18n/ko/Tooltips.ko.resx @@ -5,8 +5,6 @@ System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 공개 릴리스 페이지에서 새 버전을 확인합니다 · 몇 초 소요 - 로그와 환경 보고서를 원하는 폴더에 ZIP으로 압축합니다. 설정과 암호는 포함되지 않습니다. - 브라우저에서 릴리스 페이지를 엽니다. 브라우저에서 라이선스를 엽니다. 데이터베이스, 설정, 로그가 있는 폴더를 엽니다. 브라우저에서 공개 릴리스 페이지를 엽니다. @@ -135,7 +133,6 @@ 디스크로 옮겨진 프레임과 캐시된 썸네일을 삭제합니다. 먼저 확인을 요청합니다. 이 PC의 데이터베이스, 설정, 로그 및 캐시 Titano가 시작할 때 연결하는 서버입니다. 변경하면 로그아웃됩니다 · Enter로 적용, Esc로 되돌리기 - 로그와 환경 보고서를 원하는 폴더에 ZIP으로 압축합니다. 세션 토큰을 제외한 모든 설정을 JSON으로 저장합니다. 각 프레임의 파일 이름입니다. 예: {date}_{time}_{n:0000}. 확장자는 자동으로 추가됩니다 · Enter로 적용, Esc로 되돌리기 아카이브 폴더입니다. 예: {year}/{date} {camera}. 슬래시로 하위 폴더를 만듭니다 · Enter로 적용, Esc로 되돌리기 diff --git a/i18n/lt/Tooltips.lt.resx b/i18n/lt/Tooltips.lt.resx index 74ae1b5f..759095dd 100644 --- a/i18n/lt/Tooltips.lt.resx +++ b/i18n/lt/Tooltips.lt.resx @@ -5,8 +5,6 @@ System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 Patikrinti viešajame leidimų puslapyje, ar yra naujesnė versija · kelios sekundės - Suglaudinti žurnalus ir aplinkos ataskaitą į ZIP pasirinktame aplanke; parametrai ir slaptažodžiai neįtraukiami - Atidaryti leidimo puslapį naršyklėje Atidaryti licenciją naršyklėje Atidaryti aplanką su duomenų baze, parametrais ir žurnalais Atidaryti viešąjį leidimų puslapį naršyklėje @@ -137,7 +135,6 @@ Panaikinti iškeltus kadrus ir talpykloje esančias miniatiūras; prieš tai paklausiama Šio kompiuterio duomenų bazė, parametrai, žurnalai ir talpyklos Serveris, prie kurio Titano jungiasi paleidžiamas; jį pakeitus atsijungiama · Enter – taikyti, Esc – atšaukti - Suglaudinti žurnalus ir aplinkos ataskaitą į ZIP pasirinktame aplanke Įrašyti visus parametrus kaip JSON, be seanso prieigos rakto Kiekvieno kadro failo pavadinimas, pavyzdžiui, {date}_{time}_{n:0000}; plėtinys pridedamas · Enter – taikyti, Esc – atšaukti Archyvo aplankai, pavyzdžiui, {year}/{date} {camera}; pasvirasis brūkšnys pradeda poaplankį · Enter – taikyti, Esc – atšaukti diff --git a/i18n/lv/Tooltips.lv.resx b/i18n/lv/Tooltips.lv.resx index b33fbf6c..e403591e 100644 --- a/i18n/lv/Tooltips.lv.resx +++ b/i18n/lv/Tooltips.lv.resx @@ -5,8 +5,6 @@ System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 Meklēt jaunāku versiju publisko laidienu lapā · dažas sekundes - Saspiest žurnālus un vides pārskatu ZIP failā jūsu izvēlētā mapē; iestatījumi un paroles netiek iekļauti - Atvērt laidiena lapu pārlūkprogrammā Atvērt licenci pārlūkprogrammā Atvērt mapi ar datu bāzi, iestatījumiem un žurnāliem Atvērt publisko laidienu lapu pārlūkprogrammā @@ -137,7 +135,6 @@ Dzēst uz disku pārvietotos kadrus un kešatmiņā saglabātos sīktēlus; vispirms jautā Šī datora datu bāze, iestatījumi, žurnāli un kešatmiņas Serveris, ar kuru Titano savienojas startējot; to mainot, notiek izrakstīšanās · Enter piemēro, Esc atsauc - Saspiest žurnālus un vides pārskatu ZIP failā jūsu izvēlētā mapē Saglabāt visus iestatījumus JSON formātā bez sesijas marķiera Katra kadra faila nosaukums, piemēram, {date}_{time}_{n:0000}; paplašinājums tiek pievienots · Enter piemēro, Esc atsauc Arhīva mapes, piemēram, {year}/{date} {camera}; slīpsvītra sāk apakšmapi · Enter piemēro, Esc atsauc diff --git a/i18n/ms/Tooltips.ms.resx b/i18n/ms/Tooltips.ms.resx index 4538060b..01f5b220 100644 --- a/i18n/ms/Tooltips.ms.resx +++ b/i18n/ms/Tooltips.ms.resx @@ -5,8 +5,6 @@ System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 Tanya halaman keluaran awam tentang versi yang lebih baharu · beberapa saat - Mampatkan log dan laporan persekitaran sebagai ZIP ke dalam folder pilihan anda; tetapan dan kata laluan tidak disertakan - Buka halaman keluaran dalam pelayar Buka lesen dalam pelayar Buka folder yang mengandungi pangkalan data, tetapan dan log Buka halaman keluaran awam dalam pelayar @@ -135,7 +133,6 @@ Padam bingkai yang dilimpahkan dan lakaran kecil dalam cache; bertanya dahulu Pangkalan data, tetapan, log dan cache PC ini Pelayan yang disambungkan oleh Titano semasa mula; menukarnya akan mendaftar keluar anda · Enter untuk menggunakan, Esc untuk membatalkan - Mampatkan log dan laporan persekitaran sebagai ZIP ke dalam folder pilihan anda Simpan setiap tetapan sebagai JSON, tanpa token sesi Nama fail setiap bingkai, contohnya {date}_{time}_{n:0000}; sambungan fail ditambah · Enter untuk menggunakan, Esc untuk membatalkan Folder arkib, contohnya {year}/{date} {camera}; garis condong memulakan subfolder · Enter untuk menggunakan, Esc untuk membatalkan diff --git a/i18n/nb/Tooltips.nb.resx b/i18n/nb/Tooltips.nb.resx index 4c6b06fb..6c08eeb9 100644 --- a/i18n/nb/Tooltips.nb.resx +++ b/i18n/nb/Tooltips.nb.resx @@ -5,8 +5,6 @@ System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 Spør den offentlige utgivelsessiden om en nyere versjon · noen sekunder - Pakk loggene og en miljørapport som ZIP i en mappe du velger; innstillinger og passord er ikke med - Åpne utgivelsessiden i nettleseren Åpne lisensen i nettleseren Åpne mappen med database, innstillinger og logger Åpne den offentlige utgivelsessiden i nettleseren @@ -135,7 +133,6 @@ Slett bilder som er flyttet ut av minnet, og hurtigbufrede miniatyrbilder; spør først Database, innstillinger, logger og hurtigbuffere for denne PC-en Serveren Titano kobler til ved oppstart; hvis du endrer den, logges du av · Enter tar i bruk, Esc angrer - Pakk loggene og en miljørapport som ZIP i en mappe du velger Lagre alle innstillinger som JSON, uten økttokenet Filnavnet på hvert bilde, for eksempel {date}_{time}_{n:0000}; filtypen legges til · Enter tar i bruk, Esc angrer Arkivmapper, for eksempel {year}/{date} {camera}; en skråstrek starter en undermappe · Enter tar i bruk, Esc angrer diff --git a/i18n/nl/Tooltips.nl.resx b/i18n/nl/Tooltips.nl.resx index 7dae1c26..0cfbd9f8 100644 --- a/i18n/nl/Tooltips.nl.resx +++ b/i18n/nl/Tooltips.nl.resx @@ -5,8 +5,6 @@ System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 Vraag de openbare releasepagina naar een nieuwere versie · enkele seconden - Sla de logboeken en een omgevingsrapport als ZIP op in een map naar keuze; instellingen en wachtwoorden worden niet meegenomen - Open de releasepagina in de browser Open de licentie in de browser Open de map met database, instellingen en logboeken Open de openbare releasepagina in de browser @@ -135,7 +133,6 @@ Verwijder tijdelijk weggeschreven frames en miniaturen in de cache; vraagt eerst om bevestiging Database, instellingen, logboeken en caches van deze pc Server waarmee Titano bij het starten verbinding maakt; wijzigen meldt je af · Enter past toe, Esc maakt ongedaan - Sla de logboeken en een omgevingsrapport als ZIP op in een map naar keuze Sla alle instellingen op als JSON, zonder het sessietoken Bestandsnaam van elk frame, bijvoorbeeld {date}_{time}_{n:0000}; de extensie wordt toegevoegd · Enter past toe, Esc maakt ongedaan Archiefmappen, bijvoorbeeld {year}/{date} {camera}; een slash begint een submap · Enter past toe, Esc maakt ongedaan diff --git a/i18n/pl/Tooltips.pl.resx b/i18n/pl/Tooltips.pl.resx index 23a8dd60..41cb0bb3 100644 --- a/i18n/pl/Tooltips.pl.resx +++ b/i18n/pl/Tooltips.pl.resx @@ -5,8 +5,6 @@ System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 Sprawdź na publicznej stronie wydań, czy jest nowsza wersja · kilka sekund - Spakuj dzienniki i raport o środowisku do wybranego folderu; ustawienia i hasła nie są dołączane - Otwórz stronę wydania w przeglądarce Otwórz licencję w przeglądarce Otwórz folder z bazą danych, ustawieniami i dziennikami Otwórz publiczną stronę wydań w przeglądarce @@ -139,7 +137,6 @@ Usuń klatki przeniesione na dysk i miniatury z pamięci podręcznej; najpierw pyta o potwierdzenie Baza danych, ustawienia, dzienniki i pamięć podręczna tego komputera Serwer, z którym Titano łączy się przy uruchomieniu; jego zmiana powoduje wylogowanie · Enter stosuje, Esc przywraca - Spakuj dzienniki i raport o środowisku do wybranego folderu Zapisz wszystkie ustawienia jako JSON, bez tokenu sesji Nazwa pliku każdej klatki, np. {date}_{time}_{n:0000}; rozszerzenie jest dodawane automatycznie · Enter stosuje, Esc przywraca Foldery archiwum, np. {year}/{date} {camera}; ukośnik tworzy podfolder · Enter stosuje, Esc przywraca diff --git a/i18n/pt-BR/Tooltips.pt-BR.resx b/i18n/pt-BR/Tooltips.pt-BR.resx index 888c910d..37d48ccb 100644 --- a/i18n/pt-BR/Tooltips.pt-BR.resx +++ b/i18n/pt-BR/Tooltips.pt-BR.resx @@ -5,8 +5,6 @@ System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 Consulta a página pública de versões em busca de uma versão mais recente · alguns segundos - Compacta os logs e um relatório do ambiente em uma pasta de sua escolha; configurações e senhas não são incluídas - Abre a página da versão no navegador Abre a licença no navegador Abre a pasta com banco de dados, configurações e logs Abre a página pública de versões no navegador @@ -135,7 +133,6 @@ Exclui os quadros temporários e as miniaturas em cache; pede confirmação antes Banco de dados, configurações, logs e caches deste PC Servidor ao qual o Titano se conecta ao iniciar; alterá-lo encerra a sessão · Enter aplica, Esc reverte - Compacta os logs e um relatório do ambiente em uma pasta de sua escolha Salva todas as configurações como JSON, sem o token de sessão Nome do arquivo de cada quadro, por exemplo {date}_{time}_{n:0000}; a extensão é adicionada · Enter aplica, Esc reverte Pastas do acervo, por exemplo {year}/{date} {camera}; uma barra inicia uma subpasta · Enter aplica, Esc reverte diff --git a/i18n/pt-PT/Tooltips.pt-PT.resx b/i18n/pt-PT/Tooltips.pt-PT.resx index d68bee32..546513b1 100644 --- a/i18n/pt-PT/Tooltips.pt-PT.resx +++ b/i18n/pt-PT/Tooltips.pt-PT.resx @@ -5,8 +5,6 @@ System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 Consultar a página pública de versões à procura de uma versão mais recente · alguns segundos - Comprimir os registos e um relatório do ambiente num ZIP, numa pasta à sua escolha; as definições e as palavras-passe não são incluídas - Abrir a página da versão no browser Abrir a licença no browser Abrir a pasta com a base de dados, as definições e os registos Abrir a página pública de versões no browser @@ -135,7 +133,6 @@ Eliminar os fotogramas em cache no disco e as miniaturas em cache; pede confirmação primeiro Base de dados, definições, registos e caches deste PC Servidor a que o Titano se liga ao iniciar; alterá-lo termina a sessão · Enter aplica, Esc reverte - Comprimir os registos e um relatório do ambiente num ZIP, numa pasta à sua escolha Guardar todas as definições como JSON, sem o token de sessão Nome de ficheiro de cada fotograma, por exemplo {date}_{time}_{n:0000}; a extensão é acrescentada · Enter aplica, Esc reverte Pastas do arquivo, por exemplo {year}/{date} {camera}; uma barra inicia uma subpasta · Enter aplica, Esc reverte diff --git a/i18n/ro/Tooltips.ro.resx b/i18n/ro/Tooltips.ro.resx index 95f27835..fa971d7c 100644 --- a/i18n/ro/Tooltips.ro.resx +++ b/i18n/ro/Tooltips.ro.resx @@ -5,8 +5,6 @@ System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 Verificați pe pagina publică de versiuni dacă există o versiune mai nouă · câteva secunde - Comprimați jurnalele și un raport despre mediu într-o arhivă ZIP, într-un folder ales de dumneavoastră; setările și parolele nu sunt incluse - Deschideți pagina versiunii în browser Deschideți licența în browser Deschideți folderul cu baza de date, setările și jurnalele Deschideți pagina publică de versiuni în browser @@ -137,7 +135,6 @@ Ștergeți cadrele temporare și miniaturile din cache; se cere mai întâi confirmarea Baza de date, setările, jurnalele și memoria cache ale acestui PC Serverul la care Titano se conectează la pornire; schimbarea lui vă scoate din cont · Enter aplică, Esc anulează - Comprimați jurnalele și un raport despre mediu într-o arhivă ZIP, într-un folder ales de dumneavoastră Salvați toate setările ca JSON, fără tokenul de sesiune Numele de fișier al fiecărui cadru, de exemplu {date}_{time}_{n:0000}; extensia se adaugă automat · Enter aplică, Esc anulează Folderele arhivei, de exemplu {year}/{date} {camera}; o bară oblică începe un subfolder · Enter aplică, Esc anulează diff --git a/i18n/ru/Tooltips.ru.resx b/i18n/ru/Tooltips.ru.resx index 56ff469f..6ea436af 100644 --- a/i18n/ru/Tooltips.ru.resx +++ b/i18n/ru/Tooltips.ru.resx @@ -5,8 +5,6 @@ System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 Проверить наличие новой версии на общедоступной странице выпусков · несколько секунд - Упаковать журналы и отчёт о среде в ZIP в выбранной папке; параметры и пароли не включаются - Открыть страницу выпуска в браузере Открыть лицензию в браузере Открыть папку с базой данных, параметрами и журналами Открыть общедоступную страницу выпусков в браузере @@ -139,7 +137,6 @@ Удалить выгруженные кадры и кэшированные эскизы; сначала будет запрошено подтверждение База данных, параметры, журналы и кэши этого ПК Сервер, к которому Titano подключается при запуске; при его смене выполняется выход · Enter — применить, Esc — отменить - Упаковать журналы и отчёт о среде в ZIP в выбранной папке Сохранить все параметры в JSON, без токена сеанса Имя файла каждого кадра, например {date}_{time}_{n:0000}; расширение добавляется автоматически · Enter — применить, Esc — отменить Папки архива, например {year}/{date} {camera}; косая черта начинает вложенную папку · Enter — применить, Esc — отменить diff --git a/i18n/sk/Tooltips.sk.resx b/i18n/sk/Tooltips.sk.resx index 8a82cdf6..b0776249 100644 --- a/i18n/sk/Tooltips.sk.resx +++ b/i18n/sk/Tooltips.sk.resx @@ -5,8 +5,6 @@ System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 Vyhľadá novšiu verziu na verejnej stránke vydaní · niekoľko sekúnd - Zbalí denníky a správu o prostredí do súboru ZIP v priečinku, ktorý vyberiete; nastavenia a heslá sa nezahrnú - Otvorí stránku vydania v prehliadači Otvorí licenciu v prehliadači Otvorí priečinok s databázou, nastaveniami a denníkmi Otvorí verejnú stránku vydaní v prehliadači @@ -137,7 +135,6 @@ Odstráni odložené snímky a miniatúry vo vyrovnávacej pamäti; najprv sa opýta Databáza, nastavenia, denníky a vyrovnávacie pamäte tohto počítača Server, ku ktorému sa Titano pripája pri spustení; zmena vás odhlási · Enter použije, Esc vráti späť - Zbalí denníky a správu o prostredí do súboru ZIP v priečinku, ktorý vyberiete Uloží všetky nastavenia ako JSON, bez tokenu relácie Názov súboru každej snímky, napríklad {date}_{time}_{n:0000}; prípona sa pridá · Enter použije, Esc vráti späť Priečinky archívu, napríklad {year}/{date} {camera}; lomka začína podpriečinok · Enter použije, Esc vráti späť diff --git a/i18n/sl/Tooltips.sl.resx b/i18n/sl/Tooltips.sl.resx index c53d0097..5103e8db 100644 --- a/i18n/sl/Tooltips.sl.resx +++ b/i18n/sl/Tooltips.sl.resx @@ -5,8 +5,6 @@ System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 Preveri, ali je na javni strani izdaj novejša različica · nekaj sekund - Stisni dnevnike in poročilo o okolju v ZIP v mapi po vaši izbiri; nastavitve in gesla niso vključeni - Odpri stran izdaje v brskalniku Odpri licenco v brskalniku Odpri mapo z zbirko podatkov, nastavitvami in dnevniki Odpri javno stran izdaj v brskalniku @@ -137,7 +135,6 @@ Izbriši odložene sličice in miniature v predpomnilniku; prej vpraša Zbirka podatkov, nastavitve, dnevniki in predpomnilniki tega računalnika Strežnik, s katerim se Titano poveže ob zagonu; sprememba vas izpiše · Enter uveljavi, Esc razveljavi - Stisni dnevnike in poročilo o okolju v ZIP v mapi po vaši izbiri Shrani vse nastavitve kot JSON, brez žetona seje Ime datoteke vsake sličice, na primer {date}_{time}_{n:0000}; končnica se doda · Enter uveljavi, Esc razveljavi Mape arhiva, na primer {year}/{date} {camera}; poševnica začne podmapo · Enter uveljavi, Esc razveljavi diff --git a/i18n/sv/Tooltips.sv.resx b/i18n/sv/Tooltips.sv.resx index bb863c32..6d070a49 100644 --- a/i18n/sv/Tooltips.sv.resx +++ b/i18n/sv/Tooltips.sv.resx @@ -5,8 +5,6 @@ System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 Fråga den offentliga versionssidan efter en nyare version · några sekunder - Packa loggarna och en miljörapport som ZIP i en mapp du väljer; inställningar och lösenord ingår inte - Öppna versionssidan i webbläsaren Öppna licensen i webbläsaren Öppna mappen med databas, inställningar och loggar Öppna den offentliga versionssidan i webbläsaren @@ -135,7 +133,6 @@ Radera bildrutor i diskcachen och cachade miniatyrer; frågar först Databas, inställningar, loggar och cachar för den här datorn Server som Titano ansluter till vid start; om du ändrar den loggas du ut · Enter tillämpar, Esc återställer - Packa loggarna och en miljörapport som ZIP i en mapp du väljer Spara alla inställningar som JSON, utan sessionstoken Filnamn för varje bildruta, till exempel {date}_{time}_{n:0000}; filändelsen läggs till · Enter tillämpar, Esc återställer Arkivmappar, till exempel {year}/{date} {camera}; ett snedstreck startar en undermapp · Enter tillämpar, Esc återställer diff --git a/i18n/th/Tooltips.th.resx b/i18n/th/Tooltips.th.resx index 6705ae2e..a360352d 100644 --- a/i18n/th/Tooltips.th.resx +++ b/i18n/th/Tooltips.th.resx @@ -5,8 +5,6 @@ System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 ตรวจหาเวอร์ชันที่ใหม่กว่าจากหน้ารุ่นที่เผยแพร่สาธารณะ · ใช้เวลาไม่กี่วินาที - บีบอัดไฟล์บันทึกและรายงานสภาพแวดล้อมเป็น ZIP ลงในโฟลเดอร์ที่คุณเลือก โดยไม่รวมการตั้งค่าและรหัสผ่าน - เปิดหน้ารุ่นที่เผยแพร่ในเบราว์เซอร์ เปิดสัญญาอนุญาตในเบราว์เซอร์ เปิดโฟลเดอร์ที่มีฐานข้อมูล การตั้งค่า และไฟล์บันทึก เปิดหน้ารุ่นที่เผยแพร่สาธารณะในเบราว์เซอร์ @@ -135,7 +133,6 @@ ลบเฟรมที่ล้นออกมาและภาพขนาดย่อในแคช โดยจะถามก่อน ฐานข้อมูล การตั้งค่า ไฟล์บันทึก และแคชของพีซีนี้ เซิร์ฟเวอร์ที่ Titano เชื่อมต่อเมื่อเริ่มทำงาน การเปลี่ยนจะลงชื่อออก · Enter เพื่อใช้ Esc เพื่อย้อนกลับ - บีบอัดไฟล์บันทึกและรายงานสภาพแวดล้อมเป็น ZIP ลงในโฟลเดอร์ที่คุณเลือก บันทึกการตั้งค่าทั้งหมดเป็น JSON โดยไม่รวมโทเค็นเซสชัน ชื่อไฟล์ของแต่ละเฟรม เช่น {date}_{time}_{n:0000} โดยจะเพิ่มนามสกุลให้เอง · Enter เพื่อใช้ Esc เพื่อย้อนกลับ โฟลเดอร์ของคลังภาพ เช่น {year}/{date} {camera} เครื่องหมายทับจะเริ่มโฟลเดอร์ย่อย · Enter เพื่อใช้ Esc เพื่อย้อนกลับ diff --git a/i18n/tr/Tooltips.tr.resx b/i18n/tr/Tooltips.tr.resx index 542a2c4f..27ad42b9 100644 --- a/i18n/tr/Tooltips.tr.resx +++ b/i18n/tr/Tooltips.tr.resx @@ -5,8 +5,6 @@ System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 Herkese açık sürümler sayfasında daha yeni bir sürüm olup olmadığını denetler · birkaç saniye - Günlükleri ve bir ortam raporunu seçtiğiniz klasöre ZIP olarak paketler; ayarlar ve parolalar dahil edilmez - Sürüm sayfasını tarayıcıda açar Lisansı tarayıcıda açar Veritabanı, ayarlar ve günlüklerin bulunduğu klasörü açar Herkese açık sürümler sayfasını tarayıcıda açar @@ -135,7 +133,6 @@ Diske taşan kareleri ve önbellekteki küçük resimleri siler; önce sorar Bu bilgisayarın veritabanı, ayarları, günlükleri ve önbellekleri Titano'nun başlangıçta bağlandığı sunucu; değiştirmek oturumu kapatır · Enter uygular, Esc geri alır - Günlükleri ve bir ortam raporunu seçtiğiniz klasöre ZIP olarak paketler Tüm ayarları oturum belirteci olmadan JSON olarak kaydeder Her karenin dosya adı, örneğin {date}_{time}_{n:0000}; uzantı otomatik eklenir · Enter uygular, Esc geri alır Arşiv klasörleri, örneğin {year}/{date} {camera}; eğik çizgi bir alt klasör başlatır · Enter uygular, Esc geri alır diff --git a/i18n/uk/Tooltips.uk.resx b/i18n/uk/Tooltips.uk.resx index dd357d64..dab59177 100644 --- a/i18n/uk/Tooltips.uk.resx +++ b/i18n/uk/Tooltips.uk.resx @@ -5,8 +5,6 @@ System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 Перевірити на публічній сторінці випусків, чи є новіша версія · кілька секунд - Запакувати журнали та звіт про середовище в ZIP у вибрану вами папку; налаштування й паролі не додаються - Відкрити сторінку випуску в браузері Відкрити ліцензію в браузері Відкрити папку з базою даних, налаштуваннями та журналами Відкрити публічну сторінку випусків у браузері @@ -139,7 +137,6 @@ Видалити скинуті на диск кадри та кешовані мініатюри; спершу з’явиться запит База даних, налаштування, журнали й кеші цього ПК Сервер, до якого Titano підключається під час запуску; у разі зміни виконується вихід · Enter застосовує, Esc скасовує - Запакувати журнали та звіт про середовище в ZIP у вибрану вами папку Зберегти всі налаштування як JSON, без токена сеансу Ім’я файлу кожного кадру, наприклад {date}_{time}_{n:0000}; розширення додається автоматично · Enter застосовує, Esc скасовує Папки архіву, наприклад {year}/{date} {camera}; скісна риска починає вкладену папку · Enter застосовує, Esc скасовує diff --git a/i18n/vi/Tooltips.vi.resx b/i18n/vi/Tooltips.vi.resx index fc923efd..7d4f801a 100644 --- a/i18n/vi/Tooltips.vi.resx +++ b/i18n/vi/Tooltips.vi.resx @@ -5,8 +5,6 @@ System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 Kiểm tra trang phát hành công khai để tìm phiên bản mới hơn · mất vài giây - Nén nhật ký và báo cáo môi trường vào thư mục bạn chọn; không bao gồm cài đặt và mật khẩu - Mở trang phát hành trong trình duyệt Mở giấy phép trong trình duyệt Mở thư mục chứa cơ sở dữ liệu, cài đặt và nhật ký Mở trang phát hành công khai trong trình duyệt @@ -135,7 +133,6 @@ Xóa khung hình tràn ra và hình thu nhỏ trong bộ nhớ đệm; sẽ hỏi trước Cơ sở dữ liệu, cài đặt, nhật ký và bộ nhớ đệm của máy tính này Máy chủ Titano kết nối khi khởi động; thay đổi sẽ đăng xuất · Enter để áp dụng, Esc để hoàn tác - Nén nhật ký và báo cáo môi trường vào thư mục bạn chọn Lưu mọi cài đặt dưới dạng JSON, không kèm mã thông báo phiên Tên tệp của mỗi khung hình, ví dụ {date}_{time}_{n:0000}; phần mở rộng được thêm tự động · Enter để áp dụng, Esc để hoàn tác Thư mục kho lưu trữ, ví dụ {year}/{date} {camera}; dấu gạch chéo bắt đầu một thư mục con · Enter để áp dụng, Esc để hoàn tác diff --git a/i18n/zh-Hans/Tooltips.zh-Hans.resx b/i18n/zh-Hans/Tooltips.zh-Hans.resx index a372a266..ceb20207 100644 --- a/i18n/zh-Hans/Tooltips.zh-Hans.resx +++ b/i18n/zh-Hans/Tooltips.zh-Hans.resx @@ -5,8 +5,6 @@ System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 向公开发布页面查询是否有新版本 · 需要几秒钟 - 将日志和环境报告打包为 ZIP,保存到你选择的文件夹;不包含设置和密码 - 在浏览器中打开发布页面 在浏览器中打开许可证 打开包含数据库、设置和日志的文件夹 在浏览器中打开公开发布页面 @@ -135,7 +133,6 @@ 删除溢出的帧和缓存的缩略图;会先询问 此电脑的数据库、设置、日志和缓存 Titano 启动时连接的服务器;更改后将退出登录 · Enter 应用,Esc 还原 - 将日志和环境报告打包为 ZIP,保存到你选择的文件夹 将所有设置保存为 JSON,不含会话令牌 每一帧的文件名,例如 {date}_{time}_{n:0000};扩展名会自动添加 · Enter 应用,Esc 还原 档案库文件夹,例如 {year}/{date} {camera};斜杠表示开始一个子文件夹 · Enter 应用,Esc 还原 diff --git a/i18n/zh-Hant/Tooltips.zh-Hant.resx b/i18n/zh-Hant/Tooltips.zh-Hant.resx index 0dd71d15..f451a5de 100644 --- a/i18n/zh-Hant/Tooltips.zh-Hant.resx +++ b/i18n/zh-Hant/Tooltips.zh-Hant.resx @@ -5,8 +5,6 @@ System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 向公開發行頁面查詢是否有較新版本 · 需要幾秒鐘 - 將記錄與環境報告壓縮到您選擇的資料夾;不包含設定與密碼 - 在瀏覽器中開啟發行頁面 在瀏覽器中開啟授權條款 開啟存放資料庫、設定與記錄的資料夾 在瀏覽器中開啟公開發行頁面 @@ -135,7 +133,6 @@ 刪除溢出的影格與快取的縮圖;會先詢問 此電腦的資料庫、設定、記錄與快取 Titano 啟動時連線的伺服器;變更後會登出 · Enter 套用,Esc 還原 - 將記錄與環境報告壓縮到您選擇的資料夾 將所有設定儲存為 JSON,不含工作階段權杖 每個影格的檔名,例如 {date}_{time}_{n:0000};副檔名會自動加上 · Enter 套用,Esc 還原 典藏庫資料夾,例如 {year}/{date} {camera};斜線表示開始一個子資料夾 · Enter 套用,Esc 還原 diff --git a/src/Titano.App/About/UpdateCheck.cs b/src/Titano.App/About/UpdateCheck.cs index 8434cb88..0ad76278 100644 --- a/src/Titano.App/About/UpdateCheck.cs +++ b/src/Titano.App/About/UpdateCheck.cs @@ -4,8 +4,14 @@ using System.Text.Json; namespace Titano.App.About; -/// The newest public release (BRIEF §18). -public sealed record ReleaseInfo(Version Version, string Tag, string PageUrl); +/// The newest public release (BRIEF §18) with its downloadable files. +public sealed record ReleaseInfo(Version Version, string Tag, string PageUrl) +{ + public IReadOnlyList Assets { get; init; } = []; +} + +/// One file attached to a release. +public sealed record ReleaseAsset(string Name, string DownloadUrl, long Size); /// /// Update check against the GitHub Releases API of the public releases repository (BRIEF §18, §19.4): reads the @@ -26,7 +32,8 @@ public static class UpdateCheck return new Version(version.Major, version.Minor, Math.Max(0, version.Build)); } - /// The release described by a releases/latest response; null for drafts, pre-releases or unparsable tags. + /// The release described by a releases/latest response; null for drafts, pre-releases or unparsable tags. + /// Assets without an https download link are left out. public static ReleaseInfo? Parse(string json) { using var document = JsonDocument.Parse(json); @@ -37,7 +44,7 @@ public static class UpdateCheck var url = root.TryGetProperty("html_url", out var u) && u.ValueKind == JsonValueKind.String ? u.GetString() : null; var version = ParseVersion(tag); if (version is null || tag is null || url is null || !url.StartsWith("https://", StringComparison.OrdinalIgnoreCase)) return null; - return new ReleaseInfo(version, tag, url); + return new ReleaseInfo(version, tag, url) { Assets = ParseAssets(root) }; } /// True when is newer than (build/revision ignored). @@ -68,6 +75,22 @@ public static class UpdateCheck } } + private static List ParseAssets(JsonElement root) + { + var assets = new List(); + if (!root.TryGetProperty("assets", out var list) || list.ValueKind != JsonValueKind.Array) return assets; + foreach (var a in list.EnumerateArray()) + { + if (a.ValueKind != JsonValueKind.Object) continue; + var name = a.TryGetProperty("name", out var n) && n.ValueKind == JsonValueKind.String ? n.GetString() : null; + var link = a.TryGetProperty("browser_download_url", out var d) && d.ValueKind == JsonValueKind.String ? d.GetString() : null; + var size = a.TryGetProperty("size", out var z) && z.ValueKind == JsonValueKind.Number && z.TryGetInt64(out var bytes) ? bytes : -1; + if (string.IsNullOrEmpty(name) || link is null || !link.StartsWith("https://", StringComparison.OrdinalIgnoreCase)) continue; + assets.Add(new ReleaseAsset(name, link, size)); + } + return assets; + } + private static bool Flag(JsonElement root, string name) => root.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.True; diff --git a/src/Titano.App/About/UpdateDownload.cs b/src/Titano.App/About/UpdateDownload.cs new file mode 100644 index 00000000..0797b554 --- /dev/null +++ b/src/Titano.App/About/UpdateDownload.cs @@ -0,0 +1,251 @@ +using System.Buffers; +using System.Globalization; +using System.IO; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Security.Cryptography; + +namespace Titano.App.About; + +/// A downloaded update was refused: the release lacks a setup or checksum line, or the bytes do not match. +public sealed class UpdateVerificationException(string message) : Exception(message); + +/// +/// "Download" of the update notice (BRIEF §18, P1): fetches the package of the latest release that upgrades this copy +/// (the setup, or the portable zip for a portable copy) into a temporary folder and keeps it only when its SHA-256 +/// equals the line for it in the release's SHA256SUMS. BRIEF §8.6 does not list starting an installer among the +/// OS actions Titano may perform, so callers show the verified file in Explorer and the user runs or unpacks it. An +/// interrupted download resumes from its partial file; a transfer that stalls fails after +/// instead of hanging. +/// +public static class UpdateDownload +{ + public const string ChecksumsName = "SHA256SUMS"; + + /// A transfer that delivers no byte for this long fails (and can be resumed). + public static readonly TimeSpan IdleTimeout = TimeSpan.FromSeconds(60); + + private const string PartSuffix = ".part"; + private const int MaxChecksumsBytes = 64 * 1024; + private static readonly SearchValues Hex = SearchValues.Create("0123456789abcdefABCDEF"); + + /// + /// The file that upgrades this copy: the desktop setup ("Titano-Setup-1.2.3.exe", not the Uploader's) or, for a + /// portable copy, the portable zip ("Titano-win-x64-portable-1.2.3.zip"); null when the release has none. + /// + public static ReleaseAsset? Package(ReleaseInfo release, bool portable) + { + var (prefix, extension) = portable ? ("Titano-win-x64-portable-", ".zip") : ("Titano-Setup-", ".exe"); + return release.Assets.FirstOrDefault(a => a.Name.StartsWith(prefix, StringComparison.OrdinalIgnoreCase) + && a.Name.EndsWith(extension, StringComparison.OrdinalIgnoreCase) + && a.Name == Path.GetFileName(a.Name)); + } + + public static ReleaseAsset? Checksums(ReleaseInfo release) => release.Assets.FirstOrDefault(a => a.Name == ChecksumsName); + + /// The release carries both the package for this copy and SHA256SUMS; otherwise only its page can be opened. + public static bool CanDownload(ReleaseInfo release, bool portable) => Package(release, portable) is not null && Checksums(release) is not null; + + /// %TEMP%\Titano\updates: one folder per release below it, all owned by Titano. + public static string Root(string tempPath) => Path.Combine(tempPath, "Titano", "updates"); + + /// The folder of one release below , named after its tag. + public static string Folder(string root, ReleaseInfo release) => + Path.Combine(root, string.Concat(release.Tag.Select(c => char.IsAsciiLetterOrDigit(c) || c is '.' or '-' ? c : '_'))); + + /// + /// File name → lower-case hex SHA-256 from sha256sum output (hash name or hash *name); lines + /// that are not a 64-digit hash followed by a name are ignored. + /// + public static Dictionary ParseChecksums(string text) + { + var sums = new Dictionary(StringComparer.Ordinal); + foreach (var raw in text.Split('\n')) + { + var line = raw.TrimEnd('\r'); + if (line.Length < 66 || line[64] != ' ' || line.AsSpan(0, 64).ContainsAnyExcept(Hex)) continue; + var name = line[65..]; + if (name.StartsWith(' ') || name.StartsWith('*')) name = name[1..]; + if (name.Length > 0) sums[name] = line[..64].ToLowerInvariant(); + } + return sums; + } + + /// + /// Downloads the of for this copy into its under + /// , verifies it against SHA256SUMS and returns its path. A verified copy already there + /// is reused; an interrupted or cancelled transfer keeps its partial file for the next attempt; bytes that do not + /// verify are deleted. After a verified download the folders of other releases under are removed. + /// + /// The release cannot be verified or the bytes do not match. + /// A request failed. + /// No byte arrived for . + /// The transfer ended early or the file could not be written. + public static async Task DownloadAsync(HttpClient http, ReleaseInfo release, bool portable, string root, string userAgentVersion, + IProgress? progress, TimeSpan idleTimeout, CancellationToken ct) + { + var package = Package(release, portable) + ?? throw new UpdateVerificationException($"Release {release.Tag} has no {(portable ? "portable zip" : "Titano setup")}."); + var checksums = Checksums(release) ?? throw new UpdateVerificationException($"Release {release.Tag} has no {ChecksumsName}."); + var text = await WhileReceivingAsync(idle => ReadChecksumsAsync(http, checksums, userAgentVersion, idle.Token), idleTimeout, ct).ConfigureAwait(false); + var expected = ParseChecksums(text).GetValueOrDefault(package.Name) + ?? throw new UpdateVerificationException($"{ChecksumsName} of {release.Tag} has no line for {package.Name}."); + + var folder = Folder(root, release); + Directory.CreateDirectory(folder); + var target = Path.Combine(folder, package.Name); + if (File.Exists(target) && await HashFileAsync(target, ct).ConfigureAwait(false) == expected) + { + progress?.Report(1); + return target; + } + + var part = target + PartSuffix; + var actual = await WhileReceivingAsync(idle => DownloadToAsync(http, package, part, userAgentVersion, progress, idle, idleTimeout), idleTimeout, ct) + .ConfigureAwait(false); + if (actual != expected) + { + DeleteQuietly(part); + throw new UpdateVerificationException($"{package.Name}: SHA-256 {actual} does not match {expected} in {ChecksumsName}."); + } + File.Move(part, target, overwrite: true); + RemoveOtherReleases(root, folder); + return target; + } + + /// + /// Runs one network phase under a token that fires when nothing arrives for (the phase + /// re-arms it on every read) and reports that as a ; the caller's cancellation stays a cancellation. + /// + private static async Task WhileReceivingAsync(Func> phase, TimeSpan idleTimeout, CancellationToken ct) + { + using var idle = CancellationTokenSource.CreateLinkedTokenSource(ct); + idle.CancelAfter(idleTimeout); + try + { + return await phase(idle).ConfigureAwait(false); + } + catch (OperationCanceledException) when (idle.IsCancellationRequested && !ct.IsCancellationRequested) + { + throw new TimeoutException(string.Create(CultureInfo.InvariantCulture, $"No data received for {idleTimeout.TotalSeconds:0} s.")); + } + } + + private static async Task ReadChecksumsAsync(HttpClient http, ReleaseAsset asset, string userAgentVersion, CancellationToken ct) + { + using var response = await SendAsync(http, asset, userAgentVersion, 0, ct).ConfigureAwait(false); + if (response.Content.Headers.ContentLength > MaxChecksumsBytes) throw new UpdateVerificationException($"{ChecksumsName} is too large."); + var bytes = await response.Content.ReadAsByteArrayAsync(ct).ConfigureAwait(false); + if (bytes.Length > MaxChecksumsBytes) throw new UpdateVerificationException($"{ChecksumsName} is too large."); + return System.Text.Encoding.UTF8.GetString(bytes); + } + + /// + /// Streams the asset into , continuing an existing partial file when the server honours the + /// range request, and returns the SHA-256 of the whole file. Refuses more bytes than the release announced and + /// fails with an (partial file kept) when the transfer ends before the announced size. + /// + private static async Task DownloadToAsync(HttpClient http, ReleaseAsset asset, string path, string userAgentVersion, IProgress? progress, + CancellationTokenSource idle, TimeSpan idleTimeout) + { + var ct = idle.Token; + using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + var buffer = new byte[1 << 16]; + + // Resume only with a known size: a partial file of an unknown total cannot be checked against it. + var offset = File.Exists(path) ? new FileInfo(path).Length : 0; + if (asset.Size <= 0 || offset > asset.Size) offset = 0; + if (offset > 0 && offset == asset.Size) return await HashFileAsync(path, ct).ConfigureAwait(false); + + using var response = await SendAsync(http, asset, userAgentVersion, offset, ct).ConfigureAwait(false); + var resumed = offset > 0 && response.StatusCode == HttpStatusCode.PartialContent && response.Content.Headers.ContentRange?.From == offset; + await using var output = new FileStream(path, resumed ? FileMode.Open : FileMode.Create, FileAccess.ReadWrite, FileShare.None, 1 << 16, FileOptions.Asynchronous); + long total = 0; + if (resumed) + { + int kept; + while (total < offset && (kept = await output.ReadAsync(buffer.AsMemory(0, (int)Math.Min(buffer.Length, offset - total)), ct).ConfigureAwait(false)) > 0) + { + hash.AppendData(buffer, 0, kept); + total += kept; + } + output.SetLength(total); + } + + await using var input = await response.Content.ReadAsStreamAsync(ct).ConfigureAwait(false); + int read; + while ((read = await input.ReadAsync(buffer, ct).ConfigureAwait(false)) > 0) + { + idle.CancelAfter(idleTimeout); + total += read; + if (asset.Size > 0 && total > asset.Size) + { + await output.DisposeAsync().ConfigureAwait(false); + DeleteQuietly(path); + throw new UpdateVerificationException($"{asset.Name} is larger than the release announced."); + } + hash.AppendData(buffer, 0, read); + await output.WriteAsync(buffer.AsMemory(0, read), ct).ConfigureAwait(false); + if (asset.Size > 0) progress?.Report((double)total / asset.Size); + } + await output.FlushAsync(ct).ConfigureAwait(false); + if (asset.Size > 0 && total < asset.Size) + throw new IOException(string.Create(CultureInfo.InvariantCulture, $"{asset.Name}: the transfer ended after {total} of {asset.Size} bytes.")); + return Convert.ToHexStringLower(hash.GetHashAndReset()); + } + + private static async Task SendAsync(HttpClient http, ReleaseAsset asset, string userAgentVersion, long offset, CancellationToken ct) + { + using var request = new HttpRequestMessage(HttpMethod.Get, asset.DownloadUrl); + request.Headers.UserAgent.Add(new ProductInfoHeaderValue("Titano", userAgentVersion)); + request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/octet-stream")); + if (offset > 0) request.Headers.Range = new RangeHeaderValue(offset, null); + var response = await http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, ct).ConfigureAwait(false); + try + { + response.EnsureSuccessStatusCode(); + return response; + } + catch + { + response.Dispose(); + throw; + } + } + + /// Drops the folders of other (older) releases: only the verified setup is worth keeping. + private static void RemoveOtherReleases(string root, string keep) + { + foreach (var folder in Directory.EnumerateDirectories(root)) + { + if (string.Equals(Path.GetFullPath(folder), Path.GetFullPath(keep), StringComparison.OrdinalIgnoreCase)) continue; + try + { + Directory.Delete(folder, recursive: true); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + // A setup still open (running, scanned) stays until the next verified download. + } + } + } + + private static void DeleteQuietly(string path) + { + try + { + File.Delete(path); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + // A scanner may hold the file; the next download overwrites it. + } + } + + private static async Task HashFileAsync(string path, CancellationToken ct) + { + await using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 1 << 16, FileOptions.Asynchronous | FileOptions.SequentialScan); + return Convert.ToHexStringLower(await SHA256.HashDataAsync(stream, ct).ConfigureAwait(false)); + } +} diff --git a/src/Titano.App/About/UpdateFlow.cs b/src/Titano.App/About/UpdateFlow.cs new file mode 100644 index 00000000..e1f0c424 --- /dev/null +++ b/src/Titano.App/About/UpdateFlow.cs @@ -0,0 +1,177 @@ +using System.IO; +using System.Net.Http; +using Titano.Core.Diagnostics; +using Titano.Ui.Mvvm; + +namespace Titano.App.About; + +/// Where the update notice stands. +public enum UpdateState +{ + Unknown, + Checking, + UpToDate, + Available, + Failed, + Downloading, + Downloaded, + DownloadFailed, + NotVerified, +} + +/// What needs from the application: the running version, the mode, the network and the shell. +public sealed record UpdateHost( + Version Running, + bool IsCapture, + bool IsPortable, + Func> CheckAsync, + Func?, CancellationToken, Task> DownloadAsync, + Action OpenUrl, + Action Reveal); + +/// +/// The update notice of About and Settings › Updates (BRIEF §18): checks the latest release, downloads and verifies the +/// package that upgrades this copy (: the setup, or the portable zip for a portable copy) +/// and shows it in Explorer. Running it is left to the user because BRIEF §8.6 lets Titano only open links and show +/// files. A release without that package or without SHA256SUMS only opens its page; a capture run never touches +/// the network. The flow owns its two commands so that their can-execute state follows every change. +/// +public sealed class UpdateFlow +{ + private static readonly TimeSpan CheckTimeout = TimeSpan.FromSeconds(30); + + private readonly UpdateHost _host; + + public UpdateFlow(UpdateHost host) + { + _host = host; + Check = new AsyncRelayCommand((_, ct) => CheckAsync(ct), _ => State is not (UpdateState.Checking or UpdateState.Downloading)); + Download = new AsyncRelayCommand((_, ct) => DownloadAsync(ct), _ => IsDownloadOffered); + } + + /// Raised after every change of state, release, progress or downloaded file. + public event Action? Changed; + + public UpdateState State { get; private set; } = UpdateState.Unknown; + + /// The newer release, or null when there is none (or no check has succeeded yet). + public ReleaseInfo? Release { get; private set; } + + /// Fraction of the package downloaded so far. + public double Downloaded { get; private set; } + + /// The verified package; null until a download succeeded. + public string? PackagePath { get; private set; } + + public bool IsPortable => _host.IsPortable; + + public AsyncRelayCommand Check { get; } + + public AsyncRelayCommand Download { get; } + + /// Download is offered: a newer release exists and no verified package is waiting (a failed download can be retried). + public bool IsDownloadOffered => + Release is not null && State is UpdateState.Available or UpdateState.DownloadFailed or UpdateState.NotVerified; + + /// The package Download fetches; null when Download opens the release page instead. + public ReleaseAsset? Package => + Release is { } release && UpdateDownload.CanDownload(release, _host.IsPortable) ? UpdateDownload.Package(release, _host.IsPortable) : null; + + /// Stops a download in progress; its partial file is kept and the next Download resumes it. + public void CancelDownload() => Download.Cancel(); + + /// The start-up check (BRIEF §18): only when the user left it on and never in a capture run. + public Task CheckOnStartAsync(bool enabled) => enabled ? CheckAsync(CancellationToken.None) : Task.FromResult(null); + + /// Asks for the latest release and returns it when it is newer than the running version. + public async Task CheckAsync(CancellationToken ct) + { + if (_host.IsCapture || State is UpdateState.Checking or UpdateState.Downloading) return null; + SetState(UpdateState.Checking); + ReleaseInfo? latest = null; + var failed = true; + try + { + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct); + timeout.CancelAfter(CheckTimeout); + latest = await _host.CheckAsync(timeout.Token); + failed = false; + } + catch (Exception ex) when (ex is HttpRequestException or OperationCanceledException or IOException) + { + Log.Info("update", "Update check failed: " + ex.Message); + } + finally + { + SetResult(latest, failed); + } + return Release; + } + + /// Sets a check result without the network (capture, tests). A package already verified for the same release stays offered. + public void SetResult(ReleaseInfo? release, bool failed = false) + { + var newer = !failed && release is not null && UpdateCheck.IsNewer(release, _host.Running) ? release : null; + var keepPackage = newer is not null && PackagePath is not null && newer.Tag == Release?.Tag && File.Exists(PackagePath); + Release = newer; + if (!keepPackage) PackagePath = null; + SetState(failed ? UpdateState.Failed + : newer is null ? UpdateState.UpToDate + : keepPackage ? UpdateState.Downloaded + : UpdateState.Available); + } + + private async Task DownloadAsync(CancellationToken ct) + { + if (Release is not { } release || _host.IsCapture) return; + if (Package is null) + { + _host.OpenUrl(release.PageUrl); + return; + } + Downloaded = 0; + SetState(UpdateState.Downloading); + var progress = new Progress(fraction => + { + if (State != UpdateState.Downloading || fraction - Downloaded < 0.01) return; + Downloaded = fraction; + Changed?.Invoke(); + }); + try + { + var path = await _host.DownloadAsync(release, progress, ct); + PackagePath = path; + Log.Info("update", $"{Path.GetFileName(path)} of {release.Tag} downloaded and verified: {path}"); + SetState(UpdateState.Downloaded); + _host.Reveal(path); + } + catch (UpdateVerificationException ex) + { + Log.Warning("update", "Update download refused: " + ex.Message); + SetState(UpdateState.NotVerified); + } + catch (OperationCanceledException) when (ct.IsCancellationRequested) + { + Log.Info("update", $"Download of {release.Tag} cancelled; the next one resumes it."); + SetState(UpdateState.Available); + } + catch (Exception ex) when (ex is HttpRequestException or TimeoutException or OperationCanceledException or IOException or UnauthorizedAccessException) + { + Log.Warning("update", "Update download failed: " + ex.Message); + SetState(UpdateState.DownloadFailed); + } + finally + { + // Anything unexpected still reaches the command's error report; the notice must not stay "Downloading". + if (State == UpdateState.Downloading) SetState(UpdateState.DownloadFailed); + } + } + + private void SetState(UpdateState state) + { + State = state; + Changed?.Invoke(); + Check.RaiseCanExecuteChanged(); + Download.RaiseCanExecuteChanged(); + } +} diff --git a/src/Titano.App/Infrastructure/AppServices.cs b/src/Titano.App/Infrastructure/AppServices.cs index 5ed5098f..4744f842 100644 --- a/src/Titano.App/Infrastructure/AppServices.cs +++ b/src/Titano.App/Infrastructure/AppServices.cs @@ -38,6 +38,9 @@ public sealed class AppServices : IAsyncDisposable public static readonly TimeSpan ScanInterval = TimeSpan.FromMinutes(10); private static readonly Lazy Http = new(() => new HttpClient { Timeout = TimeSpan.FromSeconds(20) }); + + /// Update packages are large: their download fails when it stalls (), never after a fixed total time. + private static readonly Lazy DownloadHttp = new(() => new HttpClient { Timeout = Timeout.InfiniteTimeSpan }); private readonly CancellationTokenSource _stopping = new(); private readonly Dictionary _scans = []; private Task _polling = Task.CompletedTask; @@ -55,6 +58,9 @@ public sealed class AppServices : IAsyncDisposable Server = new ServerSession(settings, saveSettings, new TitanoServerApiFactory(), new DpapiTokenProtector()); Encoders = new MediaFoundationInventory(); CheckForUpdateAsync = ct => UpdateCheck.FetchAsync(Http.Value, ProductLinks.LatestReleaseApi, VersionText, ct); + DownloadUpdateAsync = (release, progress, ct) => + UpdateDownload.DownloadAsync(DownloadHttp.Value, release, environment.IsPortable, UpdateDownload.Root(Path.GetTempPath()), VersionText, progress, + UpdateDownload.IdleTimeout, ct); } public AppEnvironment Environment { get; } @@ -89,6 +95,9 @@ public sealed class AppServices : IAsyncDisposable /// Latest public release (GitHub Releases API of the releases repository, BRIEF §18). public Func> CheckForUpdateAsync { get; set; } + /// Downloads and verifies the package of a release for this copy (setup, or portable zip; BRIEF §18 P1) and returns its path. + public Func?, CancellationToken, Task> DownloadUpdateAsync { get; set; } + /// The index; null until succeeded. public TitanoDatabase? Database { get; private set; } diff --git a/src/Titano.App/Infrastructure/DiagnosticsBundle.cs b/src/Titano.App/Infrastructure/DiagnosticsBundle.cs index 1bdb5217..bb00d67c 100644 --- a/src/Titano.App/Infrastructure/DiagnosticsBundle.cs +++ b/src/Titano.App/Infrastructure/DiagnosticsBundle.cs @@ -1,58 +1,70 @@ using System.Globalization; using System.IO; -using System.IO.Compression; using System.Runtime.InteropServices; using System.Text; +using Titano.App.Settings; +using Titano.Core.Diagnostics; +using Titano.Core.Export; +using Titano.Core.Model; +using Titano.Core.Windows.Codecs; +using Titano.Data; namespace Titano.App.Infrastructure; /// -/// The diagnostics bundle of About and Settings › Advanced (BRIEF §12.9): the log files plus an environment report -/// (versions, OS, runtime, culture, folders), zipped into a folder the user chose. Settings and tokens are not included. +/// The diagnostics bundle of About and Settings › Advanced (BRIEF §12.9, §22 Phase 8): an environment report, the codec +/// and encoder inventory, the settings, the latest failed jobs and the log files, zipped into a folder the user chose. +/// Everything passes through (the saved server token, passwords and keys never leave the +/// PC) and no photo or archive file is ever included. /// public static class DiagnosticsBundle { - /// Writes "Titano diagnostics yyyy-MM-dd HHmm.zip" into and returns its path. - public static Task CreateAsync(AppEnvironment environment, string folder, IEnumerable? extraLines = null, CancellationToken ct = default) => - Task.Run(() => + /// Failed jobs included, newest first. + public const int FailedJobs = 50; + + /// + /// Writes "Titano diagnostics yyyy-MM-dd HHmm.zip" (" (2)", " (3)"… when that name is taken) into + /// and returns its path; a bundle that fails half-way leaves no file behind. Call on the UI + /// thread: the settings are captured there; detection and writing run in the background. + /// + public static Task CreateAsync(AppServices services, string folder, IEnumerable? extraLines = null, CancellationToken ct = default) + { + var settings = services.Settings.ToJson(); + var report = Report(services.Environment, extraLines) + DatabaseLine(services.Database); + return Task.Run(async () => { - var path = Path.Combine(folder, $"Titano diagnostics {DateTime.Now.ToString("yyyy-MM-dd HHmm", CultureInfo.InvariantCulture)}.zip"); + var failures = services.Database is { } db ? (await db.Jobs.ListAsync(JobState.Failed, FailedJobs, null, ct).ConfigureAwait(false)).Items : []; + var codecs = Codecs(services.Encoders); + var path = ExportNaming.Unique(folder, $"Titano diagnostics {DateTime.Now.ToString("yyyy-MM-dd HHmm", CultureInfo.InvariantCulture)}", ".zip"); var temp = path + ".tmp"; - using (var zip = ZipFile.Open(temp, ZipArchiveMode.Create)) + try { - var report = zip.CreateEntry("environment.txt", CompressionLevel.Optimal); - using (var writer = new StreamWriter(report.Open(), new UTF8Encoding(false))) + await using (var file = new FileStream(temp, FileMode.Create, FileAccess.Write, FileShare.None)) + using (var bundle = new DiagnosticsArchive(file)) { - writer.Write(Report(environment, extraLines)); - } - if (Directory.Exists(environment.LogDirectory)) - { - foreach (var log in Directory.EnumerateFiles(environment.LogDirectory, "*.log").OrderBy(f => f, StringComparer.Ordinal)) - { - ct.ThrowIfCancellationRequested(); - var entry = zip.CreateEntry("logs/" + Path.GetFileName(log), CompressionLevel.Optimal); - // The current log is open for writing: share the handle instead of copying the file. - using var source = new FileStream(log, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); - using var target = entry.Open(); - source.CopyTo(target); - } + bundle.AddText("environment.txt", report); + bundle.AddText("codecs.txt", codecs); + bundle.AddJson("settings.json", settings); + bundle.AddJobs("jobs-failed.json", failures); + bundle.AddLogs(services.Environment.LogDirectory, cancellationToken: ct); } + File.Move(temp, path); + return path; + } + finally + { + // Gone after a successful move; after a failure a half-written zip helps nobody. + if (File.Exists(temp)) File.Delete(temp); } - File.Move(temp, path, overwrite: true); - return path; }, ct); + } /// Plain-text environment report. public static string Report(AppEnvironment environment, IEnumerable? extraLines = null) { var sb = new StringBuilder(); sb.AppendLine(CultureInfo.InvariantCulture, $"Titano {AppServices.VersionText}"); - sb.AppendLine(CultureInfo.InvariantCulture, $"Created {DateTimeOffset.Now:O}"); - sb.AppendLine(CultureInfo.InvariantCulture, $"OS {RuntimeInformation.OSDescription} ({RuntimeInformation.OSArchitecture})"); - sb.AppendLine(CultureInfo.InvariantCulture, $"Runtime {RuntimeInformation.FrameworkDescription} ({RuntimeInformation.ProcessArchitecture})"); - sb.AppendLine(CultureInfo.InvariantCulture, $"Culture {CultureInfo.CurrentCulture.Name} / UI {CultureInfo.CurrentUICulture.Name}"); - sb.AppendLine(CultureInfo.InvariantCulture, $"Processors {Environment.ProcessorCount}"); - sb.AppendLine(CultureInfo.InvariantCulture, $"Memory {GC.GetGCMemoryInfo().TotalAvailableMemoryBytes / (1024 * 1024)} MB"); + sb.Append(DiagnosticsArchive.SystemReport()); sb.AppendLine(CultureInfo.InvariantCulture, $"Data {environment.DataDirectory} (portable: {environment.IsPortable})"); if (extraLines is not null) { @@ -60,6 +72,38 @@ public static class DiagnosticsBundle } return sb.ToString(); } + + private static string DatabaseLine(TitanoDatabase? database) => + database is null ? "Index not open\n" : string.Create(CultureInfo.InvariantCulture, $"Index schema {database.SchemaVersion}\n"); + + /// Graphics adapter, video encoders, WIC decoders per format and missing Store extensions. + private static string Codecs(IEncoderInventory encoders) + { + var sb = new StringBuilder(); + sb.AppendLine(CultureInfo.InvariantCulture, $"Graphics adapter: {encoders.Adapter() ?? "none"}"); + sb.AppendLine("Encoders:"); + foreach (var e in encoders.Detect()) + { + var size = e.MaxWidth > 0 ? string.Create(CultureInfo.InvariantCulture, $" max {e.MaxWidth}x{e.MaxHeight}") : string.Empty; + sb.AppendLine(CultureInfo.InvariantCulture, $" {e.Codec} · {e.DisplayName} ({(e.Hardware ? "hardware" : "software")}{(e.TenBit ? ", 10-bit" : string.Empty)}{size})"); + } + try + { + var inventory = CodecInventory.Detect(); + sb.AppendLine(CultureInfo.InvariantCulture, $"HEVC decoder: {inventory.HasHevcDecoder}; AV1 decoder: {inventory.HasAv1Decoder}"); + sb.AppendLine("Image formats (WIC):"); + foreach (var f in inventory.Formats) + { + var missing = f.MissingExtensions.Count == 0 ? string.Empty : "; missing " + string.Join(", ", f.MissingExtensions.Select(x => x.ProductName)); + sb.AppendLine(CultureInfo.InvariantCulture, $" {f.Format}: {(f.IsNative ? "native" : f.Decoder is null ? "no decoder" : "preview only")}{(f.Decoder is { } d ? $" ({d.FriendlyName} {d.Version})" : string.Empty)}{missing}"); + } + } + catch (Exception ex) when (ex is COMException or DllNotFoundException or EntryPointNotFoundException or InvalidOperationException) + { + sb.AppendLine("WIC decoders could not be listed: " + ex.Message); + } + return sb.ToString(); + } } /// diff --git a/src/Titano.App/Infrastructure/ProductLinks.cs b/src/Titano.App/Infrastructure/ProductLinks.cs index bcccb637..d085cbdc 100644 --- a/src/Titano.App/Infrastructure/ProductLinks.cs +++ b/src/Titano.App/Infrastructure/ProductLinks.cs @@ -15,7 +15,7 @@ public static class ProductLinks public static string LatestReleaseApi => $"https://api.github.com/repos/{ReleasesRepository}/releases/latest"; /// The licence (EULA) published with the releases (BRIEF §12.9). - public static string Licence => $"{Repository}/blob/HEAD/LICENSE.md"; + public static string Licence => $"{Repository}/blob/HEAD/EULA.md"; /// Where translations are reviewed by the community (BRIEF §16). public static string Issues => $"{Repository}/issues"; diff --git a/src/Titano.App/Sections/AboutView.xaml b/src/Titano.App/Sections/AboutView.xaml index 30236370..805a251a 100644 --- a/src/Titano.App/Sections/AboutView.xaml +++ b/src/Titano.App/Sections/AboutView.xaml @@ -55,8 +55,14 @@ +
${escapeHtml(tail.lines.join("\n"))}
diff --git a/src/Titano.Server/Api/DiagnosticsEndpoints.cs b/src/Titano.Server/Api/DiagnosticsEndpoints.cs new file mode 100644 index 00000000..802ef10d --- /dev/null +++ b/src/Titano.Server/Api/DiagnosticsEndpoints.cs @@ -0,0 +1,113 @@ +using System.Globalization; +using System.Text; +using System.Text.Json; +using Titano.Core.Diagnostics; +using Titano.Core.Model; +using Titano.Data; +using Titano.Data.Processing; +using Titano.Server.Configuration; +using Titano.Server.Jobs; +using Titano.Server.Security; + +namespace Titano.Server.Api; + +/// +/// GET /api/v1/server/diagnostics (BRIEF §22 Phase 8; ManageArchive): a zip with the environment report, the +/// effective configuration, the encoders, the latest failed jobs and the server logs. Everything passes through +/// (admin and database passwords, tokens and keys are removed); no archive file is included. +/// +public static class DiagnosticsEndpoints +{ + /// Failed jobs included, newest first. + public const int FailedJobs = 100; + + public static void Map(RouteGroupBuilder api) => + api.MapGet("/server/diagnostics", DownloadAsync).Requires(Permissions.ManageArchive); + + private static async Task DownloadAsync(HttpContext context, Caller caller, TitanoDatabase db, ServerOptions options, ServerState state, + JobEngineHost jobs, AuditLog audit, TimeProvider time, IServiceProvider services) + { + var ct = context.RequestAborted; + var failures = (await db.Jobs.ListAsync(JobState.Failed, FailedJobs, null, ct)).Items; + var report = Report(options, state, jobs, time); + var settings = JsonSerializer.Serialize(options, ServerOptionsJson.Default.ServerOptions); + var encoders = Encoders(services.GetService()); + + // The bundle is built in a temporary file (zip writes are synchronous and logs can be large) that no crash leaves + // behind: Windows deletes it when the handle closes; elsewhere it is unlinked at once and lives on through the + // open handle (DeleteOnClose there would unlink by name at close, possibly a newer file of the same name). + var temp = Path.GetTempFileName(); + var file = new FileStream(temp, FileMode.Create, FileAccess.ReadWrite, FileShare.None, 1 << 16, + OperatingSystem.IsWindows() ? FileOptions.DeleteOnClose : FileOptions.None); + if (!OperatingSystem.IsWindows()) File.Delete(temp); + try + { + await Task.Run(() => + { + using var bundle = new DiagnosticsArchive(file); + bundle.AddText("environment.txt", report); + bundle.AddJson("settings.json", settings); + bundle.AddText("encoders.txt", encoders); + bundle.AddJobs("jobs-failed.json", failures); + bundle.AddLogs(options.LogPath, cancellationToken: ct); + }, ct); + file.Position = 0; + } + catch + { + await file.DisposeAsync(); + throw; + } + await audit.WriteAsync(caller, context, "server_diagnostics", "server"); + context.Response.Headers.CacheControl = "no-store"; + var name = string.Create(CultureInfo.InvariantCulture, $"titano-server-diagnostics-{time.GetUtcNow():yyyyMMdd-HHmm}.zip"); + return Results.File(file, "application/zip", name); + } + + private static string Report(ServerOptions options, ServerState state, JobEngineHost jobs, TimeProvider time) + { + var sb = new StringBuilder(); + sb.AppendLine(CultureInfo.InvariantCulture, $"Titano Server {SystemEndpoints.Version} ({options.ServerName})"); + sb.Append(DiagnosticsArchive.SystemReport()); + sb.AppendLine(CultureInfo.InvariantCulture, $"Uptime {time.GetUtcNow() - state.StartedAt:d\\.hh\\:mm\\:ss}"); + sb.AppendLine(CultureInfo.InvariantCulture, $"Database {state.Database} ({options.Database})"); + sb.AppendLine(CultureInfo.InvariantCulture, $"TLS {options.TlsMode} {state.TlsFingerprint}"); + sb.AppendLine(CultureInfo.InvariantCulture, $"Workers {jobs.Workers}"); + sb.AppendLine(CultureInfo.InvariantCulture, $"Archive {options.ArchivePath} ({Space(options.ArchivePath)})"); + sb.AppendLine(CultureInfo.InvariantCulture, $"Data {options.DataPath} ({Space(options.DataPath)})"); + sb.AppendLine(CultureInfo.InvariantCulture, $"Container {File.Exists("/.dockerenv")}"); + sb.AppendLine("Set by environment: " + string.Join(", ", options.Locked)); + return sb.ToString(); + } + + private static string Encoders(ProcessingService? processing) + { + if (processing is null) return "No processing engine registered.\n"; + var sb = new StringBuilder(); + foreach (var provider in processing.Options.Encoders) + { + foreach (var c in provider.Capabilities) + { + sb.AppendLine(CultureInfo.InvariantCulture, + $"{provider.Name}: {c.Codec} {c.Name} ({(c.Hardware ? "hardware" : "software")}{(c.SupportsTenBit ? ", 10-bit" : string.Empty)}, max {c.MaxWidth}x{c.MaxHeight})"); + } + } + return sb.ToString(); + } + + private static string Space(string path) + { + try + { + if (!Directory.Exists(path)) return "missing"; + var full = Path.GetFullPath(path); + // Windows wants a drive root; Unix accepts any directory and reports the volume it is mounted on. + var drive = new DriveInfo(OperatingSystem.IsWindows() ? Path.GetPathRoot(full)! : full); + return string.Create(CultureInfo.InvariantCulture, $"{drive.AvailableFreeSpace / (1L << 30)} GB free of {drive.TotalSize / (1L << 30)} GB"); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException) + { + return "free space unknown"; + } + } +} diff --git a/src/Titano.Server/Hosting/ServerHost.cs b/src/Titano.Server/Hosting/ServerHost.cs index a06cf32f..baedd368 100644 --- a/src/Titano.Server/Hosting/ServerHost.cs +++ b/src/Titano.Server/Hosting/ServerHost.cs @@ -153,6 +153,7 @@ public static class ServerHost NodeEndpoints.Map(api); ArchiveEndpoints.Map(api); AdminEndpoints.Map(api); + DiagnosticsEndpoints.Map(api); EventEndpoints.Map(api); app.MapFallback("/api/{**path}", (HttpContext context) => ApiErrors.NotFound(context)).AllowAnonymousCaller(); } diff --git a/src/Titano.Tools/Commands/FixturesCommand.cs b/src/Titano.Tools/Commands/FixturesCommand.cs index 65d823af..291cc1ea 100644 --- a/src/Titano.Tools/Commands/FixturesCommand.cs +++ b/src/Titano.Tools/Commands/FixturesCommand.cs @@ -10,18 +10,20 @@ namespace Titano.Tools.Commands; /// §20.2): interrupted downloads resume from their .part file with an HTTP range request, every file is verified /// against its SHA-256, and verified files are skipped. An entry whose sha256 is null gets the hash of its first /// download recorded in external/recorded-hashes.json (later runs verify against it) and printed so it can be -/// copied into the manifest. +/// copied into the manifest. A fixture that cannot be fetched is reported as a GitHub warning annotation when running +/// in Actions (tests that need it skip); --allow-missing then keeps the exit code 0, so CI shows the warning +/// instead of a silently "passed" step. ///
internal sealed class FixturesCommand : ICommand { private const string RecordedHashesFile = "recorded-hashes.json"; public string Name => "fixtures"; - public string Summary => "Download and verify the CC0 RAW samples in tests/fixtures/manifest.json (--manifest, --out)"; + public string Summary => "Download and verify the CC0 RAW samples in tests/fixtures/manifest.json (--manifest, --out, --allow-missing)"; public async Task RunAsync(string[] args) { - var a = new Args(args); + var a = new Args(args, "allow-missing"); var root = Args.RepoRoot(); var manifestPath = a.Get("manifest") ?? Path.Combine(root, "tests", "fixtures", "manifest.json"); var outDir = a.Get("out") ?? Path.Combine(root, "tests", "fixtures", "external"); @@ -33,7 +35,7 @@ internal sealed class FixturesCommand : ICommand ? JsonSerializer.Deserialize>(await File.ReadAllTextAsync(recordedPath)) ?? [] : []; var newlyRecorded = new List(); - var failures = 0; + var missing = new List<(Entry Entry, string Reason)>(); using var http = new HttpClient { Timeout = TimeSpan.FromMinutes(10) }; http.DefaultRequestHeaders.UserAgent.ParseAdd("Titano.Tools/1.0 (+fixtures)"); foreach (var entry in entries) @@ -65,7 +67,7 @@ internal sealed class FixturesCommand : ICommand } catch (Exception ex) when (ex is HttpRequestException or IOException or InvalidDataException or TaskCanceledException or UnauthorizedAccessException) { - failures++; + missing.Add((entry, ex.Message)); Console.Error.WriteLine($"failed {entry.Name}: {ex.Message}"); } } @@ -75,8 +77,18 @@ internal sealed class FixturesCommand : ICommand Console.WriteLine("Recorded SHA-256 of first downloads (copy into the manifest to pin them):"); foreach (var line in newlyRecorded) Console.WriteLine(" " + line); } - Console.WriteLine(failures == 0 ? $"{entries.Count} fixture(s) ready in {outDir}" : $"{failures} of {entries.Count} fixture(s) failed"); - return failures == 0 ? 0 : 1; + if (missing.Count == 0) + { + Console.WriteLine($"{entries.Count} fixture(s) ready in {outDir}"); + return 0; + } + Console.WriteLine($"{missing.Count} of {entries.Count} fixture(s) missing; the tests that need them are skipped."); + if (Environment.GetEnvironmentVariable("GITHUB_ACTIONS") == "true") + { + var manifestFile = Path.GetRelativePath(root, manifestPath).Replace('\\', '/'); + foreach (var (entry, reason) in missing) Console.WriteLine(Annotation(manifestFile, entry, reason)); + } + return a.Has("allow-missing") ? 0 : 1; void Record(string name, string hash) { @@ -86,7 +98,22 @@ internal sealed class FixturesCommand : ICommand } } - internal sealed record Entry(string Name, Uri Url, string? Sha256, long? Size); + internal sealed record Entry(string Name, Uri Url, string? Sha256, long? Size, string? Format); + + /// A GitHub Actions warning naming the missing fixture, why, and where the fix goes. + internal static string Annotation(string manifestFile, Entry entry, string reason) + { + var message = $"{entry.Name} ({entry.Format ?? "RAW"}) could not be fetched from {entry.Url.AbsoluteUri}: {reason.TrimEnd('.')}. " + + "Its decode tests are skipped. Replace the url in the manifest (see its 'instructions')."; + return $"::warning file={Escape(manifestFile, property: true)},title={Escape("RAW fixture missing", property: true)}::{Escape(message, property: false)}"; + } + + /// Workflow-command escaping (properties also escape ':' and ','). + private static string Escape(string value, bool property) + { + var escaped = value.Replace("%", "%25", StringComparison.Ordinal).Replace("\r", "%0D", StringComparison.Ordinal).Replace("\n", "%0A", StringComparison.Ordinal); + return property ? escaped.Replace(":", "%3A", StringComparison.Ordinal).Replace(",", "%2C", StringComparison.Ordinal) : escaped; + } internal static List ReadManifest(string path) { @@ -101,7 +128,8 @@ internal sealed class FixturesCommand : ICommand throw new ToolException($"Fixture {name} needs an https URL"); var sha = f.TryGetProperty("sha256", out var s) && s.ValueKind == JsonValueKind.String ? s.GetString() : null; long? size = f.TryGetProperty("size", out var z) && z.ValueKind == JsonValueKind.Number ? z.GetInt64() : null; - entries.Add(new Entry(name, url, sha, size)); + var format = f.TryGetProperty("format", out var fm) && fm.ValueKind == JsonValueKind.String ? fm.GetString() : null; + entries.Add(new Entry(name, url, sha, size, format)); } return entries; } diff --git a/src/Titano.Tools/Titano.Tools.csproj b/src/Titano.Tools/Titano.Tools.csproj index 167ccda0..9f803e63 100644 --- a/src/Titano.Tools/Titano.Tools.csproj +++ b/src/Titano.Tools/Titano.Tools.csproj @@ -5,6 +5,9 @@ Titano.Tools Titano.Tools + + + diff --git a/tests/Titano.App.Tests/About/UpdateDownloadTests.cs b/tests/Titano.App.Tests/About/UpdateDownloadTests.cs new file mode 100644 index 00000000..cd786f39 --- /dev/null +++ b/tests/Titano.App.Tests/About/UpdateDownloadTests.cs @@ -0,0 +1,328 @@ +using System.IO; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Security.Cryptography; +using System.Text; +using Titano.App.About; +using Titano.Testing; + +namespace Titano.App.Tests.About; + +public sealed class UpdateDownloadTests(TestContext context) +{ + private const string Base = "https://github.com/o/r/releases/download/v1.0.0/"; + private const string SetupName = "Titano-Setup-1.0.0.exe"; + private const string PortableName = "Titano-win-x64-portable-1.0.0.zip"; + + private static readonly TimeSpan Idle = TimeSpan.FromSeconds(30); + private static readonly byte[] Setup = Encoding.ASCII.GetBytes(string.Concat(Enumerable.Repeat("MZ setup payload ", 20_000))); + private static readonly byte[] Portable = Encoding.ASCII.GetBytes(string.Concat(Enumerable.Repeat("PK portable zip ", 9_000))); + + [Test] + public void ChecksumLinesOfBothSha256sumModesAreRead() + { + var hash = new string('A', 64); + var sums = UpdateDownload.ParseChecksums( + $"{hash} Titano-Setup-1.0.0.exe\r\n{new string('b', 64)} *Titano-Uploader-Setup-1.0.0.exe\nnot a checksum line\n{new string('c', 63)} short.exe\n\n"); + Assert.Equal(2, sums.Count); + Assert.Equal(new string('a', 64), sums["Titano-Setup-1.0.0.exe"]); + Assert.Equal(new string('b', 64), sums["Titano-Uploader-Setup-1.0.0.exe"]); + } + + [Test] + public void ThePackageForEachKindOfCopyAndTheChecksumsAreFoundAmongTheAssets() + { + var release = UpdateCheck.Parse($$""" + { "tag_name": "v1.0.0", "html_url": "https://github.com/o/r/releases/tag/v1.0.0", "assets": [ + { "name": "Titano-Uploader-Setup-1.0.0.exe", "browser_download_url": "{{Base}}Titano-Uploader-Setup-1.0.0.exe", "size": 10 }, + { "name": "{{SetupName}}", "browser_download_url": "{{Base}}{{SetupName}}", "size": {{Setup.Length}} }, + { "name": "{{PortableName}}", "browser_download_url": "{{Base}}{{PortableName}}", "size": {{Portable.Length}} }, + { "name": "SHA256SUMS", "browser_download_url": "{{Base}}SHA256SUMS", "size": 300 }, + { "name": "evil.exe", "browser_download_url": "http://example.com/evil.exe", "size": 1 } + ] } + """)!; + Assert.Equal(4, release.Assets.Count); + Assert.Equal(SetupName, UpdateDownload.Package(release, portable: false)!.Name); + Assert.Equal(PortableName, UpdateDownload.Package(release, portable: true)!.Name); + Assert.Equal(Base + "SHA256SUMS", UpdateDownload.Checksums(release)!.DownloadUrl); + Assert.True(UpdateDownload.CanDownload(release, portable: false)); + Assert.True(UpdateDownload.CanDownload(release, portable: true)); + Assert.False(UpdateDownload.CanDownload(release with { Assets = [.. release.Assets.Where(a => a.Name != "SHA256SUMS")] }, portable: false)); + Assert.False(UpdateDownload.CanDownload(release with { Assets = [.. release.Assets.Where(a => a.Name != PortableName)] }, portable: true)); + var root = UpdateDownload.Root(Path.GetTempPath()); + Assert.True(root.EndsWith(Path.Combine("Titano", "updates"), StringComparison.Ordinal), root); + Assert.Equal(Path.Combine(root, "v1.0.0"), UpdateDownload.Folder(root, release)); + } + + [Test] + public async Task AVerifiedSetupIsKeptAndReusedWithoutDownloadingAgain() + { + var root = context.CreateTempDirectory(); + var server = new FakeReleases(Setup); + using var http = new HttpClient(server); + var reported = new List(); + + var path = await DownloadAsync(http, root, progress: new SyncProgress(reported.Add)); + Assert.Equal(Path.Combine(root, "v1.0.0", SetupName), path); + Assert.SequenceEqual(Setup, await File.ReadAllBytesAsync(path)); + Assert.Equal(1.0, reported[^1]); + Assert.Equal(1, server.PackageRequests); + Assert.SequenceEqual(new[] { SetupName }, Directory.GetFiles(Path.GetDirectoryName(path)!).Select(f => Path.GetFileName(f))); + + await DownloadAsync(http, root); + Assert.Equal(1, server.PackageRequests); + } + + [Test] + public async Task APortableCopyGetsThePortableZipNeverTheSetup() + { + var root = context.CreateTempDirectory(); + var server = new FakeReleases(Setup); + using var http = new HttpClient(server); + var path = await DownloadAsync(http, root, portable: true); + Assert.Equal(PortableName, Path.GetFileName(path)); + Assert.SequenceEqual(Portable, await File.ReadAllBytesAsync(path)); + Assert.SequenceEqual(new[] { Base + PortableName }, server.PackageUrls); + } + + [Test] + public async Task ASetupThatDoesNotMatchItsChecksumIsDeleted() + { + var root = context.CreateTempDirectory(); + var tampered = Setup.ToArray(); + tampered[^1] ^= 1; + using var http = new HttpClient(new FakeReleases(Setup) { Served = tampered }); + var error = await Assert.ThrowsAsync(() => DownloadAsync(http, root)); + Assert.Contains("does not match", error.Message); + Assert.Empty(Directory.GetFiles(root, "*", SearchOption.AllDirectories)); + } + + [Test] + public async Task ACorruptedSetupLeftFromBeforeIsReplacedByAFreshDownload() + { + var root = context.CreateTempDirectory(); + var server = new FakeReleases(Setup); + using var http = new HttpClient(server); + var target = Path.Combine(root, "v1.0.0", SetupName); + Directory.CreateDirectory(Path.GetDirectoryName(target)!); + await File.WriteAllBytesAsync(target, Setup[..1000]); + + Assert.Equal(target, await DownloadAsync(http, root)); + Assert.SequenceEqual(Setup, await File.ReadAllBytesAsync(target)); + Assert.Equal(1, server.PackageRequests); + } + + [Test] + public async Task ASetupWithoutAChecksumLineIsNeverDownloaded() + { + var root = context.CreateTempDirectory(); + var server = new FakeReleases(Setup) { Sums = $"{new string('0', 64)} Titano-Uploader-Setup-1.0.0.exe\n" }; + using var http = new HttpClient(server); + await Assert.ThrowsAsync(() => DownloadAsync(http, root)); + Assert.Equal(0, server.PackageRequests); + Assert.Empty(Directory.GetFiles(root, "*", SearchOption.AllDirectories)); + } + + [Test] + public async Task MoreBytesThanTheReleaseAnnouncedAreRefused() + { + var root = context.CreateTempDirectory(); + var longer = Setup.Concat(new byte[100]).ToArray(); + using var http = new HttpClient(new FakeReleases(Setup) { Served = longer, Sums = Sums(longer, Portable) }); + await Assert.ThrowsAsync(() => DownloadAsync(http, root)); + Assert.Empty(Directory.GetFiles(root, "*", SearchOption.AllDirectories)); + } + + [Test] + public async Task AFailedRequestLeavesNoFile() + { + var root = context.CreateTempDirectory(); + using var http = new HttpClient(new FakeReleases(Setup) { Fail = true }); + await Assert.ThrowsAsync(() => DownloadAsync(http, root)); + Assert.Empty(Directory.GetFiles(root, "*", SearchOption.AllDirectories)); + } + + [Test] + public async Task ATransferCutShortIsResumedWhereItStopped() + { + var root = context.CreateTempDirectory(); + var server = new FakeReleases(Setup) { CutAfter = 100_000 }; + using var http = new HttpClient(server); + await Assert.ThrowsAsync(() => DownloadAsync(http, root)); + var part = Path.Combine(root, "v1.0.0", SetupName + ".part"); + Assert.Equal(100_000L, new FileInfo(part).Length); + + server.CutAfter = null; + var path = await DownloadAsync(http, root); + Assert.SequenceEqual(Setup, await File.ReadAllBytesAsync(path)); + Assert.SequenceEqual(new long?[] { null, 100_000 }, server.Ranges); + Assert.FileMissing(part); + } + + [Test] + public async Task AServerThatIgnoresTheRangeStartsTheFileAgain() + { + var root = context.CreateTempDirectory(); + var server = new FakeReleases(Setup) { CutAfter = 50_000 }; + using var http = new HttpClient(server); + await Assert.ThrowsAsync(() => DownloadAsync(http, root)); + + server.CutAfter = null; + server.HonourRange = false; + var path = await DownloadAsync(http, root); + Assert.SequenceEqual(Setup, await File.ReadAllBytesAsync(path)); + } + + [Test] + public async Task ACancelledDownloadKeepsItsPartialFileForTheNextAttempt() + { + var root = context.CreateTempDirectory(); + var server = new FakeReleases(Setup) { StallAfter = 64 * 1024 }; + using var http = new HttpClient(server); + using var cts = new CancellationTokenSource(); + var reported = new List(); + var download = DownloadAsync(http, root, progress: new SyncProgress(f => + { + reported.Add(f); + cts.Cancel(); + }), ct: cts.Token); + await Assert.ThrowsAsync(() => download); + var part = Path.Combine(root, "v1.0.0", SetupName + ".part"); + Assert.Equal(64L * 1024, new FileInfo(part).Length); + + server.StallAfter = null; + Assert.SequenceEqual(Setup, await File.ReadAllBytesAsync(await DownloadAsync(http, root))); + Assert.Equal(64L * 1024, server.Ranges[^1]); + } + + [Test] + public async Task ATransferThatStallsFailsAfterTheIdleTimeout() + { + var root = context.CreateTempDirectory(); + using var http = new HttpClient(new FakeReleases(Setup) { StallAfter = 10_000 }); + var started = DateTime.UtcNow; + var error = await Assert.ThrowsAsync(() => DownloadAsync(http, root, idle: TimeSpan.FromMilliseconds(300))); + Assert.Contains("No data received", error.Message); + Assert.Less((DateTime.UtcNow - started).TotalSeconds, 20); + Assert.FileExists(Path.Combine(root, "v1.0.0", SetupName + ".part")); + } + + [Test] + public async Task AnAssetOfUnknownSizeIsStillVerified() + { + var root = context.CreateTempDirectory(); + using var http = new HttpClient(new FakeReleases(Setup)); + var release = Release() with { Assets = [new ReleaseAsset(SetupName, Base + SetupName, -1), new ReleaseAsset("SHA256SUMS", Base + "SHA256SUMS", -1)] }; + var reported = new List(); + var path = await UpdateDownload.DownloadAsync(http, release, false, root, "0.1.0", new SyncProgress(reported.Add), Idle, CancellationToken.None); + Assert.SequenceEqual(Setup, await File.ReadAllBytesAsync(path)); + Assert.Empty(reported); + } + + [Test] + public async Task AVerifiedDownloadRemovesTheFoldersOfOtherReleases() + { + var root = context.CreateTempDirectory(); + var old = Directory.CreateDirectory(Path.Combine(root, "v0.9.0")).FullName; + await File.WriteAllTextAsync(Path.Combine(old, "Titano-Setup-0.9.0.exe"), "old setup"); + using var http = new HttpClient(new FakeReleases(Setup)); + await DownloadAsync(http, root); + Assert.SequenceEqual(new[] { "v1.0.0" }, Directory.GetDirectories(root).Select(d => Path.GetFileName(d))); + } + + private static Task DownloadAsync(HttpClient http, string root, bool portable = false, IProgress? progress = null, TimeSpan? idle = null, + CancellationToken ct = default) => + UpdateDownload.DownloadAsync(http, Release(), portable, root, "0.1.0", progress, idle ?? Idle, ct); + + private static ReleaseInfo Release() => new(new Version(1, 0, 0), "v1.0.0", "https://github.com/o/r/releases/tag/v1.0.0") + { + Assets = + [ + new ReleaseAsset(SetupName, Base + SetupName, Setup.Length), + new ReleaseAsset(PortableName, Base + PortableName, Portable.Length), + new ReleaseAsset("SHA256SUMS", Base + "SHA256SUMS", 300), + ], + }; + + private static string Sums(byte[] setup, byte[] portable) => + $"{new string('1', 64)} Titano-Uploader-Setup-1.0.0.exe\n{Hash(setup)} {SetupName}\n{Hash(portable)} *{PortableName}\n"; + + private static string Hash(byte[] bytes) => Convert.ToHexStringLower(SHA256.HashData(bytes)); + + /// + /// Serves SHA256SUMS, the setup and the portable zip like GitHub's release downloads: honours single open-ended + /// ranges, and can fail, end a transfer early or stall in the middle of it. + /// + private sealed class FakeReleases(byte[] setup) : HttpMessageHandler + { + public string Sums { get; set; } = UpdateDownloadTests.Sums(setup, Portable); + + /// The setup bytes actually served (tampered or longer ones); the real setup by default. + public byte[] Served { get; set; } = setup; + + public bool Fail { get; set; } + public bool HonourRange { get; set; } = true; + public int? CutAfter { get; set; } + public int? StallAfter { get; set; } + public int PackageRequests => PackageUrls.Count; + public List PackageUrls { get; } = []; + public List Ranges { get; } = []; + + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + Assert.True(request.Headers.UserAgent.ToString().StartsWith("Titano/", StringComparison.Ordinal), "GitHub requires a User-Agent"); + var url = request.RequestUri!.AbsoluteUri; + if (url == Base + "SHA256SUMS") return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(Sums) }); + var bytes = url == Base + SetupName ? Served : url == Base + PortableName ? Portable : throw new AssertionException("Unexpected request " + url); + PackageUrls.Add(url); + var from = request.Headers.Range?.Ranges.Single().From; + Ranges.Add(from); + if (Fail) return Task.FromResult(new HttpResponseMessage(HttpStatusCode.InternalServerError)); + + var offset = HonourRange && from is { } start ? (int)start : 0; + var end = CutAfter is { } cut ? System.Math.Min(bytes.Length, offset + cut) : bytes.Length; + var body = new StreamContent(new Body(bytes[offset..end], StallAfter)); + var response = new HttpResponseMessage(offset > 0 ? HttpStatusCode.PartialContent : HttpStatusCode.OK) { Content = body }; + if (offset > 0) body.Headers.ContentRange = new ContentRangeHeaderValue(offset, bytes.Length - 1, bytes.Length); + return Task.FromResult(response); + } + } + + /// A non-seekable body (no Content-Length) that waits for cancellation once bytes are read. + private sealed class Body(byte[] bytes, int? stallAfter) : Stream + { + private int _position; + + public override bool CanRead => true; + public override bool CanSeek => false; + public override bool CanWrite => false; + public override long Length => throw new NotSupportedException(); + public override long Position { get => _position; set => throw new NotSupportedException(); } + + public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) + { + if (_position == stallAfter) await Task.Delay(Timeout.Infinite, cancellationToken); + var limit = stallAfter is { } stall && _position < stall ? stall : bytes.Length; + var count = System.Math.Min(buffer.Length, limit - _position); + bytes.AsMemory(_position, count).CopyTo(buffer); + _position += count; + return count; + } + + public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) => + ReadAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask(); + + public override int Read(byte[] buffer, int offset, int count) => ReadAsync(buffer, offset, count, CancellationToken.None).GetAwaiter().GetResult(); + public override void Flush() => throw new NotSupportedException(); + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + public override void SetLength(long value) => throw new NotSupportedException(); + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + } + + /// Reports synchronously ( would post to the thread pool). + private sealed class SyncProgress(Action report) : IProgress + { + public void Report(double value) => report(value); + } +} diff --git a/tests/Titano.App.Tests/About/UpdateFlowTests.cs b/tests/Titano.App.Tests/About/UpdateFlowTests.cs new file mode 100644 index 00000000..ca68dbcd --- /dev/null +++ b/tests/Titano.App.Tests/About/UpdateFlowTests.cs @@ -0,0 +1,208 @@ +using System.IO; +using Titano.App.About; +using Titano.Testing; +using Titano.Ui.Mvvm; + +namespace Titano.App.Tests.About; + +/// The update notice: start-up opt-out, capture runs, portable copies, failures and cancellation of the download. +[Serial] // AsyncRelayCommand.Failed is a static event +public sealed class UpdateFlowTests(TestContext context) +{ + private const string Page = "https://github.com/o/r/releases/tag/v1.0.0"; + + [Test] + public async Task TheStartUpCheckFollowsTheOptOut() + { + var host = new Host(); + var flow = host.Flow(); + Assert.Null(await flow.CheckOnStartAsync(enabled: false)); + Assert.Equal(0, host.Checks); + Assert.Equal(UpdateState.Unknown, flow.State); + + Assert.Equal("v1.0.0", (await flow.CheckOnStartAsync(enabled: true))?.Tag); + Assert.Equal(1, host.Checks); + Assert.Equal(UpdateState.Available, flow.State); + } + + [Test] + public async Task ACaptureRunNeverTouchesTheNetwork() + { + var host = new Host { IsCapture = true }; + var flow = host.Flow(); + Assert.Null(await flow.CheckOnStartAsync(enabled: true)); + Assert.Null(await flow.CheckAsync(CancellationToken.None)); + Assert.Equal(0, host.Checks); + + flow.SetResult(Release(withSetup: true, withZip: true, withSums: true)); + await RunAsync(flow.Download); + Assert.Equal(0, host.Downloads); + Assert.Empty(host.Opened); + } + + [Test] + public async Task ADownloadedSetupIsShownAndOfferedUntilANewerReleaseAppears() + { + var host = new Host { Downloaded = Path.Combine(context.CreateTempDirectory(), "Titano-Setup-1.0.0.exe") }; + File.WriteAllText(host.Downloaded, "setup"); + var flow = host.Flow(); + flow.SetResult(Release(withSetup: true, withZip: false, withSums: true)); + Assert.Equal("Titano-Setup-1.0.0.exe", flow.Package?.Name); + + await RunAsync(flow.Download); + Assert.Equal((UpdateState.Downloaded, host.Downloaded), (flow.State, flow.PackagePath)); + Assert.SequenceEqual(new[] { host.Downloaded }, host.Revealed); + Assert.False(flow.IsDownloadOffered); + + flow.SetResult(Release(withSetup: true, withZip: false, withSums: true)); + Assert.Equal(UpdateState.Downloaded, flow.State); + flow.SetResult(Release(withSetup: true, withZip: false, withSums: true) with { Version = new Version(1, 1, 0), Tag = "v1.1.0" }); + Assert.Equal((UpdateState.Available, (string?)null), (flow.State, flow.PackagePath)); + } + + [Test] + public async Task APortableCopyNeverDownloadsTheSetup() + { + var host = new Host { IsPortable = true }; + var flow = host.Flow(); + flow.SetResult(Release(withSetup: true, withZip: false, withSums: true)); + Assert.Null(flow.Package); + await RunAsync(flow.Download); + Assert.Equal(0, host.Downloads); + Assert.SequenceEqual(new[] { Page }, host.Opened); + + flow.SetResult(Release(withSetup: true, withZip: true, withSums: true)); + Assert.Equal("Titano-win-x64-portable-1.0.0.zip", flow.Package?.Name); + await RunAsync(flow.Download); + Assert.Equal(1, host.Downloads); + Assert.Equal(UpdateState.Downloaded, flow.State); + } + + [Test] + public async Task AReleaseWithoutChecksumsOnlyOpensItsPage() + { + var host = new Host(); + var flow = host.Flow(); + flow.SetResult(Release(withSetup: true, withZip: true, withSums: false)); + await RunAsync(flow.Download); + Assert.Equal(0, host.Downloads); + Assert.SequenceEqual(new[] { Page }, host.Opened); + Assert.Equal(UpdateState.Available, flow.State); + } + + [Test] + public async Task ARefusedDownloadIsReportedAndCanBeRetried() + { + var host = new Host { Failure = new UpdateVerificationException("SHA-256 mismatch") }; + var flow = host.Flow(); + flow.SetResult(Release(withSetup: true, withZip: false, withSums: true)); + await RunAsync(flow.Download); + Assert.Equal(UpdateState.NotVerified, flow.State); + Assert.True(flow.IsDownloadOffered); + Assert.True(flow.Download.CanExecute(null)); + Assert.True(flow.Check.CanExecute(null)); + } + + [Test] + public async Task AStalledDownloadFailsAndCanBeRetried() + { + var host = new Host { Failure = new TimeoutException("No data received for 60 s.") }; + var flow = host.Flow(); + flow.SetResult(Release(withSetup: true, withZip: false, withSums: true)); + await RunAsync(flow.Download); + Assert.Equal(UpdateState.DownloadFailed, flow.State); + Assert.True(flow.IsDownloadOffered); + } + + [Test] + public async Task AnUnexpectedFailureIsReportedAndNeverLeavesTheNoticeDownloading() + { + var host = new Host { Failure = new UriFormatException("bad asset link") }; + var flow = host.Flow(); + flow.SetResult(Release(withSetup: true, withZip: false, withSums: true)); + var reported = new List(); + AsyncRelayCommand.Failed += reported.Add; + try + { + await RunAsync(flow.Download); + } + finally + { + AsyncRelayCommand.Failed -= reported.Add; + } + Assert.True(reported.Single() is UriFormatException, reported.Single().GetType().Name); + Assert.Equal(UpdateState.DownloadFailed, flow.State); + Assert.True(flow.Check.CanExecute(null)); + Assert.True(flow.Download.CanExecute(null)); + } + + [Test] + public async Task CancellingADownloadOffersItAgain() + { + var host = new Host { Stall = true }; + var flow = host.Flow(); + flow.SetResult(Release(withSetup: true, withZip: false, withSums: true)); + flow.Download.Execute(null); + await host.Started.Task.WaitAsync(TimeSpan.FromSeconds(10)); + Assert.Equal(UpdateState.Downloading, flow.State); + Assert.False(flow.Check.CanExecute(null)); + + flow.CancelDownload(); + await WaitAsync(flow.Download); + Assert.Equal(UpdateState.Available, flow.State); + Assert.True(flow.IsDownloadOffered); + Assert.True(flow.Check.CanExecute(null)); + } + + private static ReleaseInfo Release(bool withSetup, bool withZip, bool withSums) + { + const string Base = "https://github.com/o/r/releases/download/v1.0.0/"; + var assets = new List(); + if (withSetup) assets.Add(new ReleaseAsset("Titano-Setup-1.0.0.exe", Base + "Titano-Setup-1.0.0.exe", 1000)); + if (withZip) assets.Add(new ReleaseAsset("Titano-win-x64-portable-1.0.0.zip", Base + "Titano-win-x64-portable-1.0.0.zip", 900)); + if (withSums) assets.Add(new ReleaseAsset("SHA256SUMS", Base + "SHA256SUMS", 300)); + return new ReleaseInfo(new Version(1, 0, 0), "v1.0.0", Page) { Assets = assets }; + } + + private static async Task RunAsync(AsyncRelayCommand command) + { + command.Execute(null); + await WaitAsync(command); + } + + private static async Task WaitAsync(AsyncRelayCommand command) + { + for (var i = 0; i < 500 && command.IsRunning; i++) await Task.Delay(10); + Assert.False(command.IsRunning, "the command did not finish"); + } + + private sealed class Host + { + public bool IsCapture { get; init; } + public bool IsPortable { get; init; } + public Exception? Failure { get; init; } + public bool Stall { get; init; } + public string Downloaded { get; init; } = "Titano-Setup-1.0.0.exe"; + public int Checks { get; private set; } + public int Downloads { get; private set; } + public List Opened { get; } = []; + public List Revealed { get; } = []; + public TaskCompletionSource Started { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + + public UpdateFlow Flow() => new(new UpdateHost(new Version(0, 9, 0), IsCapture, IsPortable, + _ => + { + Checks++; + return Task.FromResult(Release(withSetup: true, withZip: true, withSums: true)); + }, + async (_, _, ct) => + { + Downloads++; + Started.TrySetResult(); + if (Stall) await Task.Delay(Timeout.Infinite, ct); + await Task.Yield(); + return Failure is null ? Downloaded : throw Failure; + }, + Opened.Add, Revealed.Add)); + } +} diff --git a/tests/Titano.App.Tests/Windows/DiagnosticsBundleTests.cs b/tests/Titano.App.Tests/Windows/DiagnosticsBundleTests.cs new file mode 100644 index 00000000..6c344b5c --- /dev/null +++ b/tests/Titano.App.Tests/Windows/DiagnosticsBundleTests.cs @@ -0,0 +1,97 @@ +using System.IO; +using System.IO.Compression; +using Titano.App.Infrastructure; +using Titano.App.Settings; +using Titano.Core.Video; +using Titano.Testing; + +namespace Titano.App.Tests.Windows; + +/// The desktop diagnostics bundle: every entry present, the saved server token and passwords never inside. +[WindowsOnly] +public sealed class DiagnosticsBundleTests(TestContext context) +{ + private const string Token = "AQAAANCMnd8BFdERjHoAwE-saved-token"; + + [Test] + public async Task TheBundleCarriesReportsAndLogsButNoSecrets() + { + var environment = AppEnvironment.ForCapture(); + try + { + var settings = new AppSettings { Language = "en", ServerUrl = "https://nas.local:8443", ServerUsername = "alice", ProtectedToken = Token }; + var services = new AppServices(environment, settings, () => { }, new NoDialogs()) { Encoders = new OneEncoder() }; + await File.WriteAllTextAsync(Path.Combine(environment.LogDirectory, "titano-20261002.log"), $"signed in with password={Token}\n"); + + var path = await DiagnosticsBundle.CreateAsync(services, context.CreateTempDirectory(), ["Self-test H.264 Test: passed"]); + + using var zip = ZipFile.OpenRead(path); + var texts = zip.Entries.ToDictionary(e => e.FullName, e => + { + using var reader = new StreamReader(e.Open()); + return reader.ReadToEnd(); + }); + Assert.SequenceEqual(new[] { "codecs.txt", "environment.txt", "jobs-failed.json", "logs/titano-20261002.log", "settings.json" }, + texts.Keys.Order(StringComparer.Ordinal)); + foreach (var (name, text) in texts) Assert.False(text.Contains(Token, StringComparison.Ordinal), $"{name} leaks the token"); + Assert.Contains("Self-test H.264 Test: passed", texts["environment.txt"]); + Assert.Contains("Test encoder", texts["codecs.txt"]); + Assert.Contains("\"ServerUsername\": \"alice\"", texts["settings.json"]); + Assert.Contains("\"ProtectedToken\": \"[removed]\"", texts["settings.json"]); + } + finally + { + environment.DeleteCaptureData(); + } + } + + [Test] + public async Task BundlesNeverOverwriteEachOtherAndAFailedOneLeavesNothing() + { + var environment = AppEnvironment.ForCapture(); + try + { + var services = new AppServices(environment, new AppSettings { Language = "en" }, () => { }, new NoDialogs()) { Encoders = new OneEncoder() }; + await File.WriteAllTextAsync(Path.Combine(environment.LogDirectory, "titano-20261002.log"), "started\n"); + var folder = context.CreateTempDirectory(); + + var first = await DiagnosticsBundle.CreateAsync(services, folder); + var second = await DiagnosticsBundle.CreateAsync(services, folder); + Assert.NotEqual(first, second); + Assert.SequenceEqual(new[] { first, second }.Order(StringComparer.Ordinal), Directory.GetFiles(folder).Order(StringComparer.Ordinal)); + + // The encoder inventory runs after the job query and before the zip is written: cancelling there fails the + // bundle half-way, once its temporary file exists. + using var cts = new CancellationTokenSource(); + services.Encoders = new OneEncoder(cts.Cancel); + var empty = context.CreateTempDirectory(); + await Assert.ThrowsAsync(() => DiagnosticsBundle.CreateAsync(services, empty, ct: cts.Token)); + Assert.Empty(Directory.GetFiles(empty)); + } + finally + { + environment.DeleteCaptureData(); + } + } + + private sealed class OneEncoder(Action? onDetect = null) : IEncoderInventory + { + public string? Adapter() => "Test adapter"; + + public IReadOnlyList Detect() + { + onDetect?.Invoke(); + return [new EncoderRow("H.264", "Test encoder", null, EncoderSource.MediaFoundation, true, false, 4096, 2304, VideoCodec.H264)]; + } + + public Task SelfTestAsync(EncoderRow row, CancellationToken ct) => Task.FromResult(new SelfTestResult(true, 100, null)); + } + + private sealed class NoDialogs : IAppDialogs + { + public string? PickFolder(string title, string? initialFolder = null) => null; + public string? PickJsonFile(string title) => null; + public bool Confirm(ConfirmRequest request) => false; + public bool SignIn(string server, string? username, Func> signIn) => false; + } +} diff --git a/tests/Titano.Core.Tests/Diagnostics/DiagnosticsArchiveTests.cs b/tests/Titano.Core.Tests/Diagnostics/DiagnosticsArchiveTests.cs new file mode 100644 index 00000000..6e9a547e --- /dev/null +++ b/tests/Titano.Core.Tests/Diagnostics/DiagnosticsArchiveTests.cs @@ -0,0 +1,74 @@ +using System.IO.Compression; +using System.Text; +using Titano.Core.Diagnostics; +using Titano.Core.Model; +using Titano.Testing; + +namespace Titano.Core.Tests.Diagnostics; + +public sealed class DiagnosticsArchiveTests(TestContext context) +{ + private const string Secret = "correct-horse-battery"; + + [Test] + public void EveryEntryIsScrubbedAndLogsKeepTheirTail() + { + var logs = context.CreateTempDirectory(); + File.WriteAllText(Path.Combine(logs, "titano-20261001.log"), "old line\nPassword=" + Secret + "\n"); + var big = new StringBuilder(); + for (var i = 0; i < 2_000; i++) big.Append("line ").Append(i).Append(" token: ").Append(Secret).Append('\n'); + File.WriteAllText(Path.Combine(logs, "titano-20261002.log"), big.ToString()); + File.WriteAllText(Path.Combine(logs, "photo.jpg"), "not a log"); + File.SetLastWriteTimeUtc(Path.Combine(logs, "titano-20261001.log"), DateTime.UtcNow.AddDays(-1)); + + using var zip = new MemoryStream(); + using (var bundle = new DiagnosticsArchive(zip)) + { + bundle.AddText("environment.txt", DiagnosticsArchive.SystemReport() + "Server https://admin:" + Secret + "@nas:8443\n"); + bundle.AddJson("settings.json", $$"""{ "ProtectedToken": "{{Secret}}", "Theme": "Dark" }"""); + bundle.AddJobs("jobs-failed.json", + [ + new Job + { + Id = Guid.CreateVersion7(), Kind = JobKind.Render, State = JobState.Failed, Attempts = 2, Created = DateTimeOffset.UtcNow, + Error = "Upload refused: Authorization: Bearer " + Secret, LogTail = "retry with password=" + Secret, + }, + ]); + bundle.AddLogs(logs, tailBytes: 4096); + } + + zip.Position = 0; + using var archive = new ZipArchive(zip, ZipArchiveMode.Read); + var names = archive.Entries.Select(e => e.FullName).Order(StringComparer.Ordinal).ToArray(); + Assert.SequenceEqual(new[] { "environment.txt", "jobs-failed.json", "logs/titano-20261001.log", "logs/titano-20261002.log", "settings.json" }, names); + foreach (var entry in archive.Entries) + { + var text = Read(entry); + Assert.False(text.Contains(Secret, StringComparison.Ordinal), $"{entry.FullName} leaks the secret"); + } + Assert.Contains("Runtime ", Read(archive.GetEntry("environment.txt")!)); + Assert.Contains("\"Theme\": \"Dark\"", Read(archive.GetEntry("settings.json")!)); + Assert.Contains("\"kind\": \"Render\"", Read(archive.GetEntry("jobs-failed.json")!)); + + var tail = Read(archive.GetEntry("logs/titano-20261002.log")!); + Assert.True(tail.StartsWith("[first ", StringComparison.Ordinal), "a cut log says so"); + Assert.Contains("line 1999 token: [removed]", tail); + Assert.Less(tail.Length, 5_000); + } + + [Test] + public void AMissingLogFolderAddsNothing() + { + using var zip = new MemoryStream(); + using (var bundle = new DiagnosticsArchive(zip)) bundle.AddLogs(Path.Combine(context.CreateTempDirectory(), "missing")); + zip.Position = 0; + using var archive = new ZipArchive(zip, ZipArchiveMode.Read); + Assert.Empty(archive.Entries); + } + + private static string Read(ZipArchiveEntry entry) + { + using var reader = new StreamReader(entry.Open(), Encoding.UTF8); + return reader.ReadToEnd(); + } +} diff --git a/tests/Titano.Core.Tests/Diagnostics/SecretScrubberTests.cs b/tests/Titano.Core.Tests/Diagnostics/SecretScrubberTests.cs new file mode 100644 index 00000000..f6592f01 --- /dev/null +++ b/tests/Titano.Core.Tests/Diagnostics/SecretScrubberTests.cs @@ -0,0 +1,98 @@ +using System.Text.Json; +using Titano.Core.Diagnostics; +using Titano.Testing; + +namespace Titano.Core.Tests.Diagnostics; + +public sealed class SecretScrubberTests +{ + private const string Secret = "hunter2-S3cr3t!"; + + [Theory] + [Case("Host=db;Port=5432;Username=titano;Password=" + Secret + ";SslMode=prefer", "Host=db;Port=5432;Username=titano;Password=[removed];SslMode=prefer")] + [Case("TITANO_DB_PASSWORD=" + Secret, "TITANO_DB_PASSWORD=[removed]")] + [Case("DbPassword: " + Secret, "DbPassword: [removed]")] + [Case("login body {\"username\":\"alice\",\"password\":\"" + Secret + "\"}", "login body {\"username\":\"alice\",\"password\":[removed]}")] + [Case("Authorization: Bearer " + Secret, "Authorization: [removed]")] + [Case("calling with bearer abcdefghijklmnop", "calling with bearer [removed]")] + [Case("Cookie: titano_session=" + Secret + "; titano_csrf=x", "Cookie: [removed]")] + [Case("git clone https://x-access-token:" + Secret + "@github.com/o/r.git", "git clone https://x-access-token:[removed]@github.com/o/r.git")] + [Case("GET /api/v1/events?token=" + Secret + "&x=1", "GET /api/v1/events?token=[removed]&x=1")] + [Case("refresh_token='" + Secret + "' client_secret=" + Secret, "refresh_token=[removed] client_secret=[removed]")] + [Case("pushed with ghp_0123456789abcdefghijABCDEFGHIJ012345", "pushed with [removed]")] + public void SecretsInTextAreRemoved(string line, string expected) => Assert.Equal(expected, SecretScrubber.ScrubLine(line)); + + [Theory] + [Case("Host=db;Password=correct horse battery;SslMode=prefer", "Host=db;Password=[removed];SslMode=prefer")] + [Case("Host=db;Password=ab,cd;Port=5432", "Host=db;Password=[removed];Port=5432")] + [Case("Server=db;PWD='semi;colon and space';User ID=sa", "Server=db;PWD=[removed];User ID=sa")] + [Case("Host=db;Password=\"quoted, \"\" pw\";Port=5432", "Host=db;Password=[removed];Port=5432")] + [Case("TITANO_ADMIN_PASSWORD=Very Secret phrase", "TITANO_ADMIN_PASSWORD=[removed]")] + [Case("DbPassword: it's a, secret", "DbPassword: [removed]")] + [Case("login body {\"password\":\"a \\\"quoted\\\" pass, word\",\"user\":\"bob\"}", "login body {\"password\":[removed],\"user\":\"bob\"}")] + [Case("postgres://titano:p@ss@db:5432/titano", "postgres://titano:[removed]@db:5432/titano")] + [Case("https://alice:pa:ss@nas.local/api", "https://alice:[removed]@nas.local/api")] + public void PasswordsWithSpacesCommasQuotesOrAtSignsLeaveNothingBehind(string line, string expected) => + Assert.Equal(expected, SecretScrubber.ScrubLine(line)); + + [Theory] + [Case("2026-10-02T09:00:00Z Info archive: Scan of /archive found 1,204 frames in 12 sequences")] + [Case("Index open (schema 3) at C:\\Users\\alice\\AppData\\Local\\Titano\\titano.db")] + [Case("frame 0193 sha256 4f2a9c0e1b7d3a5f6e8c9b0a1d2e3f4a5b6c7d8e9f0a1b2c3d4e5f6a7b8c9d0e verified")] + [Case("Token revoked for user alice")] + [Case("")] + public void OrdinaryLinesAreKept(string line) => Assert.Equal(line, SecretScrubber.ScrubLine(line)); + + [Test] + public void PrivateKeyBlocksAreDroppedWhole() + { + var text = "before\n-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASC\nBKcwggSjAgEAAoIBAQC7\n-----END PRIVATE KEY-----\nafter"; + Assert.Equal("before\n[removed private key]\nafter", SecretScrubber.ScrubText(text)); + } + + [Test] + public void SecretNamedJsonValuesAreRemovedAndOtherStringsScrubbed() + { + var json = $$""" + { + "ServerName": "NAS", + "AdminPassword": "{{Secret}}", + "DbPassword": null, + "DbConnectionString": "Host=db;Username=titano;Password=correct horse, battery;SslMode=prefer", + "TokenLifetimeDays": 30, + "ProtectedToken": "AQAAANCMnd8BFdERjHoAwE", + "TrustedCertificates": [ { "Fingerprint": "AB:CD:EF", "Server": "nas" } ], + "Nested": { "api_key": "{{Secret}}", "SigningKeys": [ "{{Secret}}" ], "Credentials": { "User": "alice", "Value": "{{Secret}}" } } + } + """; + var scrubbed = SecretScrubber.ScrubJson(json); + Assert.False(scrubbed.Contains(Secret, StringComparison.Ordinal), scrubbed); + Assert.False(scrubbed.Contains("AQAAANCMnd8BFdERjHoAwE", StringComparison.Ordinal), scrubbed); + + using var doc = JsonDocument.Parse(scrubbed); + var root = doc.RootElement; + Assert.Equal("NAS", root.GetProperty("ServerName").GetString()); + Assert.Equal(SecretScrubber.Removed, root.GetProperty("AdminPassword").GetString()); + Assert.Equal(JsonValueKind.Null, root.GetProperty("DbPassword").ValueKind); + Assert.Equal("Host=db;Username=titano;Password=[removed];SslMode=prefer", root.GetProperty("DbConnectionString").GetString()); + Assert.False(scrubbed.Contains("horse", StringComparison.Ordinal), scrubbed); + Assert.Equal(30, root.GetProperty("TokenLifetimeDays").GetInt32()); + Assert.Equal("AB:CD:EF", root.GetProperty("TrustedCertificates")[0].GetProperty("Fingerprint").GetString()); + Assert.Equal(SecretScrubber.Removed, root.GetProperty("Nested").GetProperty("Credentials").GetProperty("User").GetString()); + } + + [Test] + public void TextThatIsNotJsonIsScrubbedAsText() => + Assert.Equal("password=[removed]\n{ \"kept\": 1", SecretScrubber.ScrubJson("password=" + Secret + "\r\n{ \"kept\": 1")); + + [Theory] + [Case("DbPassword", true)] + [Case("SIGN_PFX_BASE64", true)] + [Case("X-Titano-Token", true)] + [Case("set-cookie", true)] + [Case("privateKey", true)] + [Case("ServerName", false)] + [Case("TlsCert", false)] + [Case("SessionKey", false)] + public void SecretNamesAreRecognised(string name, bool secret) => Assert.Equal(secret, SecretScrubber.IsSecretName(name)); +} diff --git a/tests/Titano.Data.Tests/Perf/LibraryPerfTests.cs b/tests/Titano.Data.Tests/Perf/LibraryPerfTests.cs new file mode 100644 index 00000000..d8b33241 --- /dev/null +++ b/tests/Titano.Data.Tests/Perf/LibraryPerfTests.cs @@ -0,0 +1,86 @@ +using Titano.Core.Model; +using Titano.Data.Repositories; +using Titano.Data.Tests.Infrastructure; +using Titano.Testing; + +namespace Titano.Data.Tests.Perf; + +/// +/// §1.1 / Phase 3 gate on the 500,000-photo library: the Library opens (archive totals, filter lists and the first +/// page, exactly what the Library screen asks at start) in under 1 s on its first query through a new connection pool, +/// and every filter, search and sort answers its first page plus the total in under 200 ms. The index was just written +/// by the same machine, so the OS page cache (and PostgreSQL's shared buffers) are warm: the gate covers query plans +/// and indexes, not a disk read after a reboot. Opt-in: TITANO_PERF=1. +/// +[Category("perf")] +[RequiresEnvironment(PerfGate.Variable)] +[Serial] +[Timeout(3_600_000)] +public abstract class LibraryPerfTests(TestContext context) : RepositoryTest(context) +{ + public const double OpenBudgetMs = 1_000; + public const double FilterBudgetMs = 200; + + [Test] + public async Task TheLibraryOpensAndFiltersWithinTheGates() + { + var options = await NewOptionsAsync(multiConnection: true); + await using (var build = await TitanoDatabase.OpenAsync(options, Ct)) await SyntheticLibrary.BuildAsync(build, Context); + + // A new connection pool and SQLite page cache, as at application start. + var db = Own(await TitanoDatabase.OpenAsync(options, Ct)); + var first = await PerfGate.TimeAsync(() => OpenLibraryAsync(db)); + var again = await PerfGate.MedianAsync(() => OpenLibraryAsync(db)); + Context.Log($"perf: {Dialect} library open {first:F0} ms first, {again:F0} ms again (budget {OpenBudgetMs:F0} ms)"); + + var failures = new List(); + if (first > OpenBudgetMs) failures.Add($"open {first:F0} ms"); + var firstPage = await db.Sequences.ListAsync(new SequenceQuery { Limit = 200 }, Ct); + foreach (var (name, query) in Filters(firstPage.NextCursor)) + { + var ms = await PerfGate.MedianAsync(async () => + { + await db.Sequences.ListAsync(query, Ct); + if (query.Cursor is null) await db.Sequences.CountAsync(query, Ct); + }); + Context.Log($"perf: {Dialect} {name} {ms:F1} ms (budget {FilterBudgetMs:F0} ms)"); + if (ms > FilterBudgetMs) failures.Add($"{name} {ms:F0} ms"); + } + Assert.True(failures.Count == 0, "over budget: " + string.Join(", ", failures)); + } + + /// What the Library screen loads when it opens: totals and filter lists, then the first page. + private async Task OpenLibraryAsync(TitanoDatabase db) + { + await db.Sequences.GetStatsAsync(null, Ct); + await db.Tags.ListAsync(Ct); + await db.Archives.ListAsync(Ct); + await db.Sequences.ListAsync(new SequenceQuery { Limit = 200 }, Ct); + } + + private static IEnumerable<(string Name, SequenceQuery Query)> Filters(string? secondPage) + { + yield return ("year", new SequenceQuery { Year = 2021, Limit = 200 }); + yield return ("camera", new SequenceQuery { Camera = "Canon EOS R5", Limit = 200 }); + yield return ("tag", new SequenceQuery { Tag = SyntheticLibrary.Tag(0), Limit = 200 }); + yield return ("status", new SequenceQuery { WithoutStatus = SequenceStatus.AnalyzedLight, Limit = 200 }); + yield return ("search", new SequenceQuery { Text = "harbour", Limit = 200 }); + yield return ("search-miss", new SequenceQuery { Text = "no such words", Limit = 200 }); + yield return ("combined", new SequenceQuery { Year = 2024, Camera = "ILCE-7M4", WithStatus = SequenceStatus.Verified, Limit = 200 }); + yield return ("sort-title", new SequenceQuery { Sort = SequenceSort.Title, Limit = 200 }); + yield return ("sort-size", new SequenceQuery { Sort = SequenceSort.Size, Limit = 200 }); + yield return ("sort-frames", new SequenceQuery { Sort = SequenceSort.FrameCount, Limit = 200 }); + yield return ("next-page", new SequenceQuery { Limit = 200, Cursor = secondPage }); + } +} + +public sealed class SqlitePerfLibraryTests(TestContext context) : LibraryPerfTests(context) +{ + protected override Backend Backend => Backend.SqliteFile; +} + +[RequiresEnvironment(PgTestServer.Variable)] +public sealed class PostgresPerfLibraryTests(TestContext context) : LibraryPerfTests(context) +{ + protected override Backend Backend => Backend.Postgres; +} diff --git a/tests/Titano.Data.Tests/Perf/PerfGate.cs b/tests/Titano.Data.Tests/Perf/PerfGate.cs new file mode 100644 index 00000000..2283b14f --- /dev/null +++ b/tests/Titano.Data.Tests/Perf/PerfGate.cs @@ -0,0 +1,26 @@ +using System.Diagnostics; + +namespace Titano.Data.Tests.Perf; + +/// Timing helpers of the opt-in performance gates (TITANO_PERF=1, category perf). +internal static class PerfGate +{ + public const string Variable = "TITANO_PERF"; + + public static async Task TimeAsync(Func action) + { + var watch = Stopwatch.StartNew(); + await action(); + return watch.Elapsed.TotalMilliseconds; + } + + /// Median of timed runs after one untimed warm-up. + public static async Task MedianAsync(Func action, int runs = 5) + { + await action(); + var times = new double[runs]; + for (var i = 0; i < runs; i++) times[i] = await TimeAsync(action); + Array.Sort(times); + return times[runs / 2]; + } +} diff --git a/tests/Titano.Data.Tests/Perf/RebuildPerfTests.cs b/tests/Titano.Data.Tests/Perf/RebuildPerfTests.cs new file mode 100644 index 00000000..757ed21c --- /dev/null +++ b/tests/Titano.Data.Tests/Perf/RebuildPerfTests.cs @@ -0,0 +1,117 @@ +using System.Diagnostics; +using System.Globalization; +using System.Text.Json; +using Titano.Core.Archiving; +using Titano.Core.Model; +using Titano.Data.Archiving; +using Titano.Data.Tests.Archiving; +using Titano.Data.Tests.Infrastructure; +using Titano.Testing; + +namespace Titano.Data.Tests.Perf; + +/// +/// Phase 2 gate, §1.1 scaled to one fifth: 400 sequences of 250 real photos (100,000 frames; the §1.1 shape has 2,000 +/// such sequences) adopted from files, then the index thrown away and rebuilt from the archive — once with the index +/// snapshot the scan left behind and once from the sidecars alone. The rebuilt index must equal the original in every +/// column of every sequence and frame (only , the time of the rebuild, may differ), +/// within a fifth of the 10 minutes §1.1 allows for 500,000 photos. Opt-in: TITANO_PERF=1. +/// +[Category("perf")] +[RequiresEnvironment(PerfGate.Variable)] +[Serial] +[Timeout(3_600_000)] +public abstract class RebuildPerfTests(TestContext context) : DatabaseTest(context) +{ + public const int Scale = 5; + public const int Sequences = SyntheticLibrary.Sequences / Scale; + public const int FramesPerSequence = SyntheticLibrary.FramesPerSequence; + public const double RebuildBudgetSeconds = 600.0 / Scale; + + private static readonly JsonSerializerOptions Json = new() { WriteIndented = false }; + + [Test] + public async Task AHundredThousandFrameArchiveRebuildsFromSidecarsAlone() + { + var root = Context.CreateTempDirectory("archive"); + var watch = Stopwatch.StartNew(); + Parallel.For(0, Sequences, new ParallelOptions { CancellationToken = Ct }, s => + { + var start = ArchiveFixture.Start.AddDays(3 * s); + var folder = Path.Combine(root, start.Year.ToString(CultureInfo.InvariantCulture), $"{start:yyyy-MM-dd} Roof {s:000}", "originals"); + Photos.WriteSeries(folder, start, FramesPerSequence, firstSeed: 1 + s * FramesPerSequence); + }); + Context.Log($"perf: wrote {Sequences * FramesPerSequence:N0} photos in {Sequences:N0} folders in {watch.Elapsed.TotalSeconds:F1} s"); + + var (db, service, archive) = await OpenIndexAsync(root, adopt: true); + watch.Restart(); + var adopted = await service.Indexer.ScanAsync(archive, ScanMode.Full, null, _ => ValueTask.CompletedTask, Ct); + Context.Log($"perf: {Dialect} adopted {adopted.Adopted} folders in {watch.Elapsed.TotalSeconds:F1} s"); + Assert.Equal(Sequences, adopted.Adopted); + Assert.Empty(adopted.Failed); + var original = await DumpAsync(db, archive.Id); + Assert.Equal(Sequences * (FramesPerSequence + 1), original.Count); + + foreach (var snapshot in new[] { true, false }) + { + if (!snapshot) File.Delete(new ArchivePaths(root).SnapshotPath); + var (freshDb, fresh, reopened) = await OpenIndexAsync(root, adopt: false); + watch.Restart(); + var rebuilt = await fresh.Indexer.ScanAsync(reopened, ScanMode.Rebuild, null, _ => ValueTask.CompletedTask, Ct); + var seconds = watch.Elapsed.TotalSeconds; + Context.Log($"perf: {Dialect} rebuilt {Sequences * FramesPerSequence:N0} frames {(snapshot ? "with" : "without")} the snapshot in {seconds:F1} s (budget {RebuildBudgetSeconds:F0} s)"); + Assert.Equal((Sequences, 0), (rebuilt.Indexed, rebuilt.Adopted)); + AssertSameIndex(original, await DumpAsync(freshDb, reopened.Id)); + Assert.Less(seconds, RebuildBudgetSeconds, "rebuild from sidecars"); + } + } + + /// A new empty index of this test's dialect with the archive at adopted or opened in it. + private async Task<(TitanoDatabase Db, ArchiveService Service, Archive Archive)> OpenIndexAsync(string root, bool adopt) + { + var db = Own(await TitanoDatabase.OpenAsync(await NewOptionsAsync(multiConnection: true), Ct)); + var service = new ArchiveService(db, new ArchiveServiceOptions { Owner = "perf", LeaseWait = TimeSpan.FromSeconds(20) }); + var archive = adopt ? await service.AdoptAsync(root, "Main", Ct) : await service.OpenAsync(root, Ct); + return (db, service, archive); + } + + /// Every sequence and frame row as JSON with all its columns, in folder and index order. + private async Task> DumpAsync(TitanoDatabase db, Guid archiveId) + { + var rows = new List(); + foreach (var location in await db.Sequences.ListLocationsAsync(archiveId, Ct)) + { + var sequence = JsonSerializer.SerializeToNode((await db.Sequences.GetAsync(location.Id, Ct))!, Json)!.AsObject(); + sequence.Remove(nameof(Sequence.UpdatedAt)); + rows.Add("S " + sequence.ToJsonString(Json)); + var after = -1; + while (await db.Frames.ListBySequenceAsync(location.Id, after, 1000, Ct) is { Count: > 0 } page) + { + rows.AddRange(page.Select(f => " F " + JsonSerializer.Serialize(f, Json))); + after = page[^1].Index; + } + } + return rows; + } + + /// Equal row for row; a difference names its first row instead of printing two 100,000-line dumps. + private static void AssertSameIndex(List expected, List actual) + { + for (var i = 0; i < System.Math.Min(expected.Count, actual.Count); i++) + { + if (expected[i] != actual[i]) Assert.Fail($"row {i} differs after the rebuild:\n before {expected[i]}\n after {actual[i]}"); + } + Assert.Equal(expected.Count, actual.Count, "rows after the rebuild"); + } +} + +public sealed class SqliteRebuildPerfTests(TestContext context) : RebuildPerfTests(context) +{ + protected override Backend Backend => Backend.SqliteFile; +} + +[RequiresEnvironment(PgTestServer.Variable)] +public sealed class PostgresRebuildPerfTests(TestContext context) : RebuildPerfTests(context) +{ + protected override Backend Backend => Backend.Postgres; +} diff --git a/tests/Titano.Data.Tests/Perf/SyntheticLibrary.cs b/tests/Titano.Data.Tests/Perf/SyntheticLibrary.cs new file mode 100644 index 00000000..8034de8b --- /dev/null +++ b/tests/Titano.Data.Tests/Perf/SyntheticLibrary.cs @@ -0,0 +1,119 @@ +using System.Diagnostics; +using Titano.Core.Imaging; +using Titano.Core.Model; +using Titano.Testing; + +namespace Titano.Data.Tests.Perf; + +/// +/// The §1.1 library: 2,000 sequences of 250 photos (500,000 frames) over twelve years, a dozen cameras, sixty tags and +/// mixed status flags, written straight into the index (no files). Everything but ids and hashes follows the seed, so +/// every run measures the same library. +/// +internal static class SyntheticLibrary +{ + public const int Sequences = 2_000; + public const int FramesPerSequence = 250; + public const int Photos = Sequences * FramesPerSequence; + + public static readonly (string Make, string Model)[] Cameras = + [ + ("Canon", "Canon EOS R5"), ("Canon", "Canon EOS 5D Mark IV"), ("Canon", "Canon EOS R6"), ("NIKON CORPORATION", "NIKON Z 7_2"), + ("NIKON CORPORATION", "NIKON D850"), ("SONY", "ILCE-7M4"), ("SONY", "ILCE-7RM5"), ("FUJIFILM", "X-T5"), ("FUJIFILM", "GFX100S"), + ("Panasonic", "DC-S5M2"), ("OM Digital Solutions", "OM-1"), ("GoPro", "HERO12 Black"), + ]; + + private static readonly string[] Subjects = + ["Harbour", "Milky Way", "Storm front", "Construction site", "City lights", "Glacier", "Sunrise", "Aurora", "Harvest", "Tide", "Fog", "Market"]; + + private static readonly string[] Places = + ["Dolomites", "Trieste", "Lofoten", "Atacama", "Iceland", "Rome", "Garda", "Etna", "Patagonia", "Namib", "Kyoto", "Sardinia"]; + + private static readonly ImageFileFormat[] Formats = [ImageFileFormat.Cr3, ImageFileFormat.Nef, ImageFileFormat.Arw, ImageFileFormat.Jpeg, ImageFileFormat.Raf, ImageFileFormat.Dng]; + + public static string Tag(int i) => i switch + { + 0 => "milky way", + 1 => "harbour", + 2 => "client", + _ => $"tag {i:00}", + }; + + /// Writes the library into and returns its archive. + public static async Task BuildAsync(TitanoDatabase db, TestContext context, int seed = 7) + { + var watch = Stopwatch.StartNew(); + var archive = new Archive { Id = Guid.CreateVersion7(), Name = "Perf", RootPath = "/archive/perf", Created = DateTimeOffset.UtcNow }; + await db.Archives.UpsertAsync(archive, context.Cancellation); + var random = new Random(seed); + var sequences = new List(Sequences); + for (var i = 0; i < Sequences; i++) + { + var (make, model) = Cameras[random.Next(Cameras.Length)]; + var first = new DateTime(2015, 1, 1).AddDays(random.Next(12 * 365)).AddMinutes(random.Next(24 * 60)); + var interval = 2 + random.Next(30); + var status = (random.Next(4) > 0 ? SequenceStatus.AnalyzedLight : 0) | (random.Next(3) == 0 ? SequenceStatus.ProxiesBuilt : 0) + | (random.Next(2) == 0 ? SequenceStatus.Verified : 0) | (random.Next(10) == 0 ? SequenceStatus.HasWarnings : 0); + var tags = Enumerable.Range(0, random.Next(5)).Select(_ => Tag(random.Next(60))).Distinct().ToArray(); + sequences.Add(new Sequence + { + Id = Guid.CreateVersion7(), + ArchiveId = archive.Id, + Title = random.Next(8) == 0 ? null : $"{Subjects[random.Next(Subjects.Length)]} {Places[random.Next(Places.Length)]} {i}", + Folder = $"{first.Year}/{first:yyyy-MM-dd}_{i:0000}", + CameraMake = make, + CameraModel = model, + FirstCapture = first, + LastCapture = first.AddSeconds(interval * (FramesPerSequence - 1)), + FrameCount = FramesPerSequence, + MedianInterval = interval, + TotalBytes = FramesPerSequence * 25_000_000L, + Status = status, + Rating = random.Next(6), + Tags = tags, + UpdatedAt = DateTimeOffset.UtcNow, + }); + } + foreach (var s in sequences) await db.Sequences.UpsertAsync(s, context.Cancellation); + await db.Frames.BulkInsertAsync(sequences.SelectMany((s, i) => Frames(s, seed, i)), context.Cancellation); + context.Log($"perf: built {Sequences:N0} sequences / {Photos:N0} photos in {watch.Elapsed.TotalSeconds:F1} s"); + return archive; + } + + private static IEnumerable Frames(Sequence sequence, int seed, int index) + { + // Seeded by the sequence's position, not its random id, so every run builds the same frames. + var random = new Random(unchecked((seed * 100_003) + index)); + var format = Formats[random.Next(Formats.Length)]; + for (var i = 0; i < FramesPerSequence; i++) + { + var flags = random.Next(2_000) switch + { + 0 => FrameFlags.Missing, + 1 => FrameFlags.Corrupt, + 2 or 3 => FrameFlags.Duplicate, + _ => FrameFlags.None, + }; + yield return new Frame + { + Id = Guid.CreateVersion7(), + SequenceId = sequence.Id, + Index = i, + RelativePath = $"{sequence.Folder}/originals/IMG_{i:0000}.{format.ToString().ToUpperInvariant()}", + FileName = $"IMG_{i:0000}.{format.ToString().ToUpperInvariant()}", + Size = 20_000_000 + random.Next(10_000_000), + Sha256 = Convert.ToHexStringLower(Guid.NewGuid().ToByteArray()) + Convert.ToHexStringLower(Guid.NewGuid().ToByteArray()), + CapturedAt = sequence.FirstCapture!.Value.AddSeconds(sequence.MedianInterval!.Value * i), + TimestampSource = TimestampSource.ExifOriginal, + ExposureTime = 1 / 250.0, + FNumber = 8, + Iso = 100, + FocalLength = 24, + Width = 6000, + Height = 4000, + Format = format, + Flags = flags, + }; + } + } +} diff --git a/tests/Titano.Server.Tests/Api/DiagnosticsTests.cs b/tests/Titano.Server.Tests/Api/DiagnosticsTests.cs new file mode 100644 index 00000000..1139c28b --- /dev/null +++ b/tests/Titano.Server.Tests/Api/DiagnosticsTests.cs @@ -0,0 +1,70 @@ +using System.IO.Compression; +using System.Net; +using System.Text.Json; +using Titano.Core.Model; +using Titano.Testing; + +namespace Titano.Server.Tests.Api; + +[Category("server")] +public sealed class DiagnosticsTests(TestContext context) +{ + private const string DbPassword = "db-secret-pw-42"; + private const string ConnectionPassword = "correct horse, \"battery\" staple"; + + [Test] + public async Task TheBundleHoldsReportsLogsAndFailuresWithoutSecrets() + { + await using var server = await TestServer.StartAsync(context, o => o.DbPassword = DbPassword); + var admin = await server.AdminAsync(); + // Only reported, never opened: the test server already runs on its own database. + server.Options.DbConnectionString = $"Host=db;Username=titano;Password={ConnectionPassword};SslMode=prefer"; + Directory.CreateDirectory(server.Options.LogPath); + await File.WriteAllTextAsync(Path.Combine(server.Options.LogPath, "titano-server-test.log"), + $"connecting with Password={DbPassword}\nAuthorization: Bearer {TestServer.Password}\n"); + var job = new Job { Id = Guid.CreateVersion7(), Kind = JobKind.Render, State = JobState.Queued, Created = DateTimeOffset.UtcNow }; + await server.Database.Jobs.EnqueueAsync(job); + await server.Database.Jobs.SetStateAsync(job.Id, JobState.Failed, "rejected: token=" + DbPassword + " for db"); + + using var response = await admin.GetAsync("/api/v1/server/diagnostics"); + await response.ExpectAsync(HttpStatusCode.OK); + Assert.Equal("application/zip", response.Content.Headers.ContentType?.MediaType); + await using var body = await response.Content.ReadAsStreamAsync(); + using var zip = new ZipArchive(body, ZipArchiveMode.Read); + var texts = zip.Entries.ToDictionary(e => e.FullName, Read); + + Assert.Contains("environment.txt", texts.Keys); + Assert.Contains("encoders.txt", texts.Keys); + Assert.Contains("logs/titano-server-test.log", texts.Keys); + foreach (var (name, text) in texts) + { + Assert.False(text.Contains(DbPassword, StringComparison.Ordinal), $"{name} leaks the database password"); + Assert.False(text.Contains(TestServer.AdminPassword, StringComparison.Ordinal), $"{name} leaks the admin password"); + Assert.False(text.Contains(TestServer.Password, StringComparison.Ordinal), $"{name} leaks a user password"); + Assert.False(text.Contains("horse", StringComparison.Ordinal) || text.Contains("staple", StringComparison.Ordinal), $"{name} leaks the connection-string password"); + } + Assert.Contains("Titano Server ", texts["environment.txt"]); + using (var settings = JsonDocument.Parse(texts["settings.json"])) + { + Assert.Equal("[removed]", settings.RootElement.GetProperty("DbPassword").GetString()); + Assert.Equal("[removed]", settings.RootElement.GetProperty("AdminPassword").GetString()); + Assert.Equal("Host=db;Username=titano;Password=[removed];SslMode=prefer", settings.RootElement.GetProperty("DbConnectionString").GetString()); + } + using (var failed = JsonDocument.Parse(texts["jobs-failed.json"])) + { + var entry = failed.RootElement.EnumerateArray().Single(); + Assert.Equal(("Render", "rejected: token=[removed]"), (entry.GetProperty("kind").GetString(), entry.GetProperty("error").GetString())); + } + + var (viewer, _, _) = await server.UserAsync("vera", "viewer"); + using var refused = await viewer.GetAsync("/api/v1/server/diagnostics"); + await refused.ExpectErrorAsync(HttpStatusCode.Forbidden, "forbidden"); + Assert.NotEmpty((await server.Database.Audit.ListAsync(null, "server_diagnostics", 10, null)).Items); + } + + private static string Read(ZipArchiveEntry entry) + { + using var reader = new StreamReader(entry.Open()); + return reader.ReadToEnd(); + } +} diff --git a/tests/Titano.Tools.Tests/FixturesCommandTests.cs b/tests/Titano.Tools.Tests/FixturesCommandTests.cs new file mode 100644 index 00000000..190a5bbb --- /dev/null +++ b/tests/Titano.Tools.Tests/FixturesCommandTests.cs @@ -0,0 +1,37 @@ +using Titano.Testing; +using Titano.Tools.Commands; + +namespace Titano.Tools.Tests; + +/// The fixtures command reports a sample it cannot fetch instead of passing silently (BRIEF §20.2). +public sealed class FixturesCommandTests(TestContext context) +{ + [Test] + public void TheWarningAnnotationNamesTheFixtureAndEscapesWorkflowCommandCharacters() + { + var entry = new FixturesCommand.Entry("canon-eos-r5.cr3", new Uri("https://raw.pixls.us/data/Canon/EOS%20R5/IMG_0001.CR3"), null, null, "Cr3"); + var line = FixturesCommand.Annotation("tests/fixtures/manifest.json", entry, "Response status code 404, 100% missing\r\nretry later."); + Assert.Equal( + "::warning file=tests/fixtures/manifest.json,title=RAW fixture missing::canon-eos-r5.cr3 (Cr3) could not be fetched from " + + "https://raw.pixls.us/data/Canon/EOS%2520R5/IMG_0001.CR3: Response status code 404, 100%25 missing%0D%0Aretry later. " + + "Its decode tests are skipped. Replace the url in the manifest (see its 'instructions').", + line); + Assert.True(FixturesCommand.Annotation("a:b,c.json", entry, "x").StartsWith("::warning file=a%3Ab%2Cc.json,title=", StringComparison.Ordinal)); + } + + [Test] + public async Task AMissingFixtureFailsTheCommandUnlessMissingFilesAreAllowed() + { + var folder = context.CreateTempDirectory(); + var manifest = Path.Combine(folder, "manifest.json"); + // Port 1 refuses the connection at once (or the proxy answers with an error): the fixture stays missing. + await File.WriteAllTextAsync(manifest, """ + { "files": [ { "name": "missing.dng", "url": "https://127.0.0.1:1/missing.dng", "sha256": null, "size": null, "format": "Dng" } ] } + """); + var output = Path.Combine(folder, "external"); + + Assert.Equal(1, await new FixturesCommand().RunAsync(["--manifest", manifest, "--out", output])); + Assert.Equal(0, await new FixturesCommand().RunAsync(["--manifest", manifest, "--out", output, "--allow-missing"])); + Assert.FileMissing(Path.Combine(output, "missing.dng")); + } +} diff --git a/tests/Titano.Tools.Tests/Program.cs b/tests/Titano.Tools.Tests/Program.cs new file mode 100644 index 00000000..9668382f --- /dev/null +++ b/tests/Titano.Tools.Tests/Program.cs @@ -0,0 +1,8 @@ +using Titano.Testing; + +namespace Titano.Tools.Tests; + +internal static class TestMain +{ + public static Task Main(string[] args) => TestRunner.RunAsync(args, typeof(TestMain).Assembly); +} diff --git a/tests/Titano.Tools.Tests/Titano.Tools.Tests.csproj b/tests/Titano.Tools.Tests/Titano.Tools.Tests.csproj new file mode 100644 index 00000000..280ec8d0 --- /dev/null +++ b/tests/Titano.Tools.Tests/Titano.Tools.Tests.csproj @@ -0,0 +1,11 @@ + + + Exe + net10.0 + Titano.Tools.Tests + + + + + + diff --git a/tests/fixtures/manifest.json b/tests/fixtures/manifest.json index 73815b4d..2fed2c8e 100644 --- a/tests/fixtures/manifest.json +++ b/tests/fixtures/manifest.json @@ -1,5 +1,13 @@ { - "description": "CC0 RAW samples from raw.pixls.us (one per managed RAW decoder), fetched by 'Titano.Tools fixtures' into tests/fixtures/external (git-ignored, CI-cached on this file). sha256 null: the first download records its hash in external/recorded-hashes.json and prints it for pinning here. width/height: size the managed decoder develops (before orientation). urlVerified false: the URL follows the site's data/// layout but was written without network access; replace it with the sample's download link if the fetch reports 404.", + "description": "CC0 RAW samples from raw.pixls.us (one per managed RAW decoder), fetched by 'Titano.Tools fixtures' into tests/fixtures/external (not committed; CI caches it keyed on this file). sha256 null: the first download records its hash in external/recorded-hashes.json and prints it for pinning here. width/height: size the managed decoder develops (before orientation). urlVerified false: the URL follows the site's data/// layout but was written without network access and may 404; CI then shows a 'RAW fixture missing' warning and the decode tests for that file are skipped.", + "instructions": [ + "1. Open https://raw.pixls.us/ and find the camera (make, model) of the entry; pick a sample whose licence column says CC0.", + "2. Copy that sample's download link (a https://raw.pixls.us/data/... URL) into 'url' and set 'urlVerified' to true.", + "3. Run 'dotnet run --project src/Titano.Tools -- fixtures': it downloads into tests/fixtures/external and prints the SHA-256 of each first download.", + "4. Copy each printed hash into 'sha256' and the file length into 'size', so later runs verify the exact file.", + "5. Run 'dotnet run --project src/Titano.Tools -- diagnose tests/fixtures/external' and set 'width'/'height' to the developed size it reports (before orientation).", + "6. Run 'dotnet run --project tests/Titano.Core.Tests -- --filter ExternalFixture' and commit the manifest (never the downloaded files)." + ], "license": "CC0-1.0", "files": [ {