From d0beb7d3bf0fac1e9f032b7b2b560ee9f19e000d Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 22:15:21 +0000 Subject: [PATCH 01/12] ci(release): publish the public releases repository; fix signing and token conditions The step conditions read step-level env, which a step's own if cannot see: signing never ran and every release went to this repository. Secrets now surface as job-level HAS_* flags. The publish job sets up .NET for make-icon, re-publishing a tag updates the existing release, the portable zip carries portable.txt, and tags are validated before anything is built. deploy/releases-repo holds the public README, EULA draft, SECURITY policy and issue forms; release.yml copies them with the Unraid template, compose file, screenshots, i18n and SHA256SUMS. The fixtures command reports missing samples as warning annotations (--allow-missing) instead of a silent pass. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- .github/workflows/ci.yml | 5 +- .github/workflows/release.yml | 188 +++++++++++++----- .../.github/ISSUE_TEMPLATE/bug_report.yml | 67 +++++++ .../.github/ISSUE_TEMPLATE/config.yml | 5 + .../ISSUE_TEMPLATE/translation_review.yml | 49 +++++ deploy/releases-repo/EULA.md | 108 ++++++++++ deploy/releases-repo/README.md | 119 +++++++++++ deploy/releases-repo/SECURITY.md | 48 +++++ src/Titano.App/Infrastructure/ProductLinks.cs | 2 +- src/Titano.Tools/Commands/FixturesCommand.cs | 46 ++++- tests/fixtures/manifest.json | 10 +- 11 files changed, 588 insertions(+), 59 deletions(-) create mode 100644 deploy/releases-repo/.github/ISSUE_TEMPLATE/bug_report.yml create mode 100644 deploy/releases-repo/.github/ISSUE_TEMPLATE/config.yml create mode 100644 deploy/releases-repo/.github/ISSUE_TEMPLATE/translation_review.yml create mode 100644 deploy/releases-repo/EULA.md create mode 100644 deploy/releases-repo/README.md create mode 100644 deploy/releases-repo/SECURITY.md diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 926ad0c4..e5a00411 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -64,10 +64,9 @@ jobs: if: runner.os == 'Windows' run: dotnet format whitespace Titano.slnx --verify-no-changes + # 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 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 03ecd78e..24222a51 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,15 @@ 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. RELEASES_REPO: ${{ vars.RELEASES_REPO || format('{0}/titano-releases', github.repository_owner) }} jobs: @@ -28,12 +36,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 +58,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: @@ -59,6 +76,15 @@ jobs: 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 + 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" @@ -68,7 +94,7 @@ jobs: 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 +102,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 +137,43 @@ 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 + previous="$(git describe --tags --abbrev=0 "$TAG^" 2>/dev/null || true)" + 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/ docker: needs: version runs-on: ubuntu-latest + outputs: + image: ${{ steps.image.outputs.name }} steps: - uses: actions/checkout@v4 with: @@ -158,49 +207,98 @@ 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 + run: | + if [ "$HAS_RELEASES_TOKEN" = "true" ]; then + echo "repo=$RELEASES_REPO" >> "$GITHUB_OUTPUT" + else + echo "repo=$GITHUB_REPOSITORY" >> "$GITHUB_OUTPUT" + 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 + + - name: Update the public releases repository + if: env.HAS_RELEASES_TOKEN == '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 + owner="${RELEASES_REPO%%/*}" + 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 image owner. + 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#${RELEASES_REPO}#g" -e "s#ghcr.io/alby96/#ghcr.io/${owner,,}/#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: GitHub release env: - RELEASES_TOKEN: ${{ secrets.RELEASES_TOKEN }} - GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + GH_TOKEN: ${{ env.HAS_RELEASES_TOKEN == 'true' && secrets.RELEASES_TOKEN || secrets.GITHUB_TOKEN }} + TARGET: ${{ steps.target.outputs.repo }} 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 + 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" + else + gh release create "$TAG" out/release/* --repo "$TARGET" --title "Titano $VERSION" --notes-file out/release-notes.md --prerelease="$PRERELEASE" + fi + + - name: Summary + env: + TARGET: ${{ steps.target.outputs.repo }} + run: | + { + echo "## Titano $VERSION" + echo "- Release: https://github.com/$TARGET/releases/tag/$TAG" + echo "- Image: \`$IMAGE:$VERSION\`$([ "$PRERELEASE" = "false" ] && 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/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..724a373f --- /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 › *Export 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..d56c0f72 --- /dev/null +++ b/deploy/releases-repo/README.md @@ -0,0 +1,119 @@ +# 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 *Review* 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. 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 › *Export bundle*; 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/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.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/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": [ { From 85d091d1feb20e5219df955e7bf3df9ebcf67db2 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 22:20:45 +0000 Subject: [PATCH 02/12] feat(app): download the update and verify it against SHA256SUMS Download now fetches the desktop setup of the latest release into %TEMP%\Titano\updates\, keeps it only when its SHA-256 matches the release's SHA256SUMS line, and shows it in Explorer. BRIEF 8.6 does not list starting an installer among the allowed shell actions, so the user runs it. A release without a setup or SHA256SUMS still opens its page; capture runs never download. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- i18n/en/About.resx | 5 + i18n/en/Tooltips.resx | 3 +- i18n/it/About.it.resx | 5 + i18n/it/Tooltips.it.resx | 3 +- src/Titano.App/About/UpdateCheck.cs | 31 +++- src/Titano.App/About/UpdateDownload.cs | 165 ++++++++++++++++++ src/Titano.App/Infrastructure/AppServices.cs | 8 + src/Titano.App/Sections/AboutView.xaml | 3 + src/Titano.App/Sections/AboutViewModel.cs | 80 ++++++++- src/Titano.App/Sections/SettingsView.xaml | 3 + .../About/UpdateDownloadTests.cs | 145 +++++++++++++++ 11 files changed, 436 insertions(+), 15 deletions(-) create mode 100644 src/Titano.App/About/UpdateDownload.cs create mode 100644 tests/Titano.App.Tests/About/UpdateDownloadTests.cs diff --git a/i18n/en/About.resx b/i18n/en/About.resx index ce8aea99..1dc68f3f 100644 --- a/i18n/en/About.resx +++ b/i18n/en/About.resx @@ -23,6 +23,11 @@ Checking… Up to date Download + Download failed + Downloading {0:P0} Check failed + Download not verified + Titano {0} downloaded + Show setup Updates diff --git a/i18n/en/Tooltips.resx b/i18n/en/Tooltips.resx index 7ca6cbe4..a815b5e5 100644 --- a/i18n/en/Tooltips.resx +++ b/i18n/en/Tooltips.resx @@ -6,11 +6,12 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 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 + Download the setup, check it against the release's SHA-256 list and show it in Explorer · tens of MB 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 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 diff --git a/i18n/it/About.it.resx b/i18n/it/About.it.resx index 2370ca1e..2f871e07 100644 --- a/i18n/it/About.it.resx +++ b/i18n/it/About.it.resx @@ -23,6 +23,11 @@ Verifica in corso… Aggiornato Scarica + Download non riuscito + Download in corso {0:P0} Verifica non riuscita + Download non verificato + Titano {0} scaricato + Mostra installer Aggiornamenti diff --git a/i18n/it/Tooltips.it.resx b/i18n/it/Tooltips.it.resx index c81ad08f..1eba743f 100644 --- a/i18n/it/Tooltips.it.resx +++ b/i18n/it/Tooltips.it.resx @@ -6,11 +6,12 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 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 + Scarica l'installer, lo confronta con l'elenco SHA-256 della versione e lo mostra in Esplora file · decine di MB 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 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 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..7fade974 --- /dev/null +++ b/src/Titano.App/About/UpdateDownload.cs @@ -0,0 +1,165 @@ +using System.Buffers; +using System.IO; +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 desktop setup of the latest release 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 it. +/// +public static class UpdateDownload +{ + public const string ChecksumsName = "SHA256SUMS"; + private const int MaxChecksumsBytes = 64 * 1024; + private static readonly SearchValues Hex = SearchValues.Create("0123456789abcdefABCDEF"); + + /// The desktop setup ("Titano-Setup-1.2.3.exe"), not the Uploader's. + public static ReleaseAsset? Installer(ReleaseInfo release) => + release.Assets.FirstOrDefault(a => a.Name.StartsWith("Titano-Setup-", StringComparison.OrdinalIgnoreCase) + && a.Name.EndsWith(".exe", 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 a setup and SHA256SUMS; otherwise only its page can be opened. + public static bool CanDownload(ReleaseInfo release) => Installer(release) is not null && Checksums(release) is not null; + + /// %TEMP%\Titano\updates\<tag> under . + public static string Folder(string tempRoot, ReleaseInfo release) => + Path.Combine(tempRoot, "Titano", "updates", 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 setup of into , verifies it against + /// SHA256SUMS and returns its path. A verified copy already there is reused; a partial or mismatching + /// download is deleted. + /// + /// The release cannot be verified or the bytes do not match. + /// A request failed. + public static async Task DownloadAsync(HttpClient http, ReleaseInfo release, string folder, string userAgentVersion, IProgress? progress, + CancellationToken ct) + { + var installer = Installer(release) ?? throw new UpdateVerificationException($"Release {release.Tag} has no Titano setup."); + var checksums = Checksums(release) ?? throw new UpdateVerificationException($"Release {release.Tag} has no {ChecksumsName}."); + var expected = ParseChecksums(await ReadChecksumsAsync(http, checksums, userAgentVersion, ct).ConfigureAwait(false)).GetValueOrDefault(installer.Name) + ?? throw new UpdateVerificationException($"{ChecksumsName} of {release.Tag} has no line for {installer.Name}."); + + Directory.CreateDirectory(folder); + var target = Path.Combine(folder, installer.Name); + if (File.Exists(target) && await HashFileAsync(target, ct).ConfigureAwait(false) == expected) + { + progress?.Report(1); + return target; + } + + var part = target + ".part"; + try + { + var actual = await DownloadToAsync(http, installer, part, userAgentVersion, progress, ct).ConfigureAwait(false); + if (actual != expected) throw new UpdateVerificationException($"{installer.Name}: SHA-256 {actual} does not match {expected} in {ChecksumsName}."); + File.Move(part, target, overwrite: true); + return target; + } + finally + { + DeleteQuietly(part); + } + } + + private static async Task ReadChecksumsAsync(HttpClient http, ReleaseAsset asset, string userAgentVersion, CancellationToken ct) + { + using var response = await SendAsync(http, asset, userAgentVersion, 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 , hashing as it goes; refuses more bytes than the release announced. + private static async Task DownloadToAsync(HttpClient http, ReleaseAsset asset, string path, string userAgentVersion, IProgress? progress, + CancellationToken ct) + { + using var response = await SendAsync(http, asset, userAgentVersion, ct).ConfigureAwait(false); + var length = asset.Size > 0 ? asset.Size : response.Content.Headers.ContentLength ?? -1; + await using var input = await response.Content.ReadAsStreamAsync(ct).ConfigureAwait(false); + await using var output = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, 1 << 16, FileOptions.Asynchronous); + using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + var buffer = new byte[1 << 16]; + long total = 0; + int read; + while ((read = await input.ReadAsync(buffer, ct).ConfigureAwait(false)) > 0) + { + total += read; + if (asset.Size > 0 && total > asset.Size) 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 (length > 0) progress?.Report(Math.Min(1.0, (double)total / length)); + } + await output.FlushAsync(ct).ConfigureAwait(false); + return Convert.ToHexStringLower(hash.GetHashAndReset()); + } + + private static async Task SendAsync(HttpClient http, ReleaseAsset asset, string userAgentVersion, 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")); + var response = await http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, ct).ConfigureAwait(false); + try + { + response.EnsureSuccessStatusCode(); + return response; + } + catch + { + response.Dispose(); + throw; + } + } + + private static void DeleteQuietly(string path) + { + try + { + File.Delete(path); + } + catch (IOException) + { + // A scanner may hold the partial file; %TEMP% cleanup removes it later. + } + catch (UnauthorizedAccessException) + { + } + } + + 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/Infrastructure/AppServices.cs b/src/Titano.App/Infrastructure/AppServices.cs index 5ed5098f..d6dc5a8d 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) }); + + /// Setups are large: the download is bounded by the caller's cancellation, not a short timeout. + private static readonly Lazy DownloadHttp = new(() => new HttpClient { Timeout = TimeSpan.FromMinutes(30) }); private readonly CancellationTokenSource _stopping = new(); private readonly Dictionary _scans = []; private Task _polling = Task.CompletedTask; @@ -55,6 +58,8 @@ 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, UpdateDownload.Folder(Path.GetTempPath(), release), VersionText, progress, ct); } public AppEnvironment Environment { get; } @@ -89,6 +94,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 setup of a release (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/Sections/AboutView.xaml b/src/Titano.App/Sections/AboutView.xaml index 30236370..7b445788 100644 --- a/src/Titano.App/Sections/AboutView.xaml +++ b/src/Titano.App/Sections/AboutView.xaml @@ -57,6 +57,9 @@ +
${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..07c7dfe5 --- /dev/null +++ b/src/Titano.Server/Api/DiagnosticsEndpoints.cs @@ -0,0 +1,108 @@ +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 self-deleting temporary file: zip writes are synchronous and logs can be large. + var file = new FileStream(Path.GetTempFileName(), FileMode.Create, FileAccess.ReadWrite, FileShare.None, 1 << 16, FileOptions.DeleteOnClose); + 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/tests/Titano.App.Tests/Windows/DiagnosticsBundleTests.cs b/tests/Titano.App.Tests/Windows/DiagnosticsBundleTests.cs new file mode 100644 index 00000000..6bb5a4ca --- /dev/null +++ b/tests/Titano.App.Tests/Windows/DiagnosticsBundleTests.cs @@ -0,0 +1,65 @@ +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(); + } + } + + private sealed class OneEncoder : IEncoderInventory + { + public string? Adapter() => "Test adapter"; + + public IReadOnlyList Detect() => + [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..0daa141e --- /dev/null +++ b/tests/Titano.Core.Tests/Diagnostics/SecretScrubberTests.cs @@ -0,0 +1,84 @@ +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("client_secret=" + Secret + " refresh_token='" + Secret + "'", "client_secret=[removed] refresh_token=[removed]")] + [Case("pushed with ghp_0123456789abcdefghijABCDEFGHIJ012345", "pushed with [removed]")] + public void SecretsInTextAreRemoved(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;Password={{Secret}}", + "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;Password=[removed]", root.GetProperty("DbConnectionString").GetString()); + 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] {", SecretScrubber.ScrubJson("password=" + Secret + " {")); + + [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.Server.Tests/Api/DiagnosticsTests.cs b/tests/Titano.Server.Tests/Api/DiagnosticsTests.cs new file mode 100644 index 00000000..d3e4063e --- /dev/null +++ b/tests/Titano.Server.Tests/Api/DiagnosticsTests.cs @@ -0,0 +1,65 @@ +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"; + + [Test] + public async Task TheBundleHoldsReportsLogsAndFailuresWithoutSecrets() + { + await using var server = await TestServer.StartAsync(context, o => o.DbPassword = DbPassword); + var admin = await server.AdminAsync(); + 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, "token=" + DbPassword + " rejected"); + + 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.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()); + } + using (var failed = JsonDocument.Parse(texts["jobs-failed.json"])) + { + var entry = failed.RootElement.EnumerateArray().Single(); + Assert.Equal(("Render", "token=[removed] rejected"), (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(); + } +} From 7170943c68e2efcfaedf4fccde431028ba179cee Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 22:35:30 +0000 Subject: [PATCH 04/12] test(perf): opt-in gates for the 500k-photo library and the 100k-frame rebuild Category perf, skipped unless TITANO_PERF=1. A synthetic library of 2,000 sequences and 500,000 frames (SQLite, and PostgreSQL when TITANO_TEST_PG is set) must open the Library in under 1 s cold and answer every filter, search, sort and next page in under 200 ms; a 100,000-frame archive adopted from real files must rebuild from its sidecars, with and without the index snapshot, into the identical index within the scaled 2-minute budget. perf.yml runs them weekly and on demand against PostgreSQL 17 and writes the timings to the job summary. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- .github/workflows/perf.yml | 73 +++++++++++ .../Perf/LibraryPerfTests.cs | 84 +++++++++++++ tests/Titano.Data.Tests/Perf/PerfGate.cs | 26 ++++ .../Perf/RebuildPerfTests.cs | 85 +++++++++++++ .../Perf/SyntheticLibrary.cs | 117 ++++++++++++++++++ 5 files changed, 385 insertions(+) create mode 100644 .github/workflows/perf.yml create mode 100644 tests/Titano.Data.Tests/Perf/LibraryPerfTests.cs create mode 100644 tests/Titano.Data.Tests/Perf/PerfGate.cs create mode 100644 tests/Titano.Data.Tests/Perf/RebuildPerfTests.cs create mode 100644 tests/Titano.Data.Tests/Perf/SyntheticLibrary.cs diff --git a/.github/workflows/perf.yml b/.github/workflows/perf.yml new file mode 100644 index 00000000..5e43f70b --- /dev/null +++ b/.github/workflows/perf.yml @@ -0,0 +1,73 @@ +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 '```' + grep -h "perf:" out-perf.log 2>/dev/null | sed 's/^ *//' || echo "no timings recorded" + 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/tests/Titano.Data.Tests/Perf/LibraryPerfTests.cs b/tests/Titano.Data.Tests/Perf/LibraryPerfTests.cs new file mode 100644 index 00000000..ffbcc0ed --- /dev/null +++ b/tests/Titano.Data.Tests/Perf/LibraryPerfTests.cs @@ -0,0 +1,84 @@ +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 a cold index, and every filter, search and +/// sort answers its first page plus the total in under 200 ms. 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 page cache, as at application start. + var db = Own(await TitanoDatabase.OpenAsync(options, Ct)); + var cold = await PerfGate.TimeAsync(() => OpenLibraryAsync(db)); + var warm = await PerfGate.MedianAsync(() => OpenLibraryAsync(db)); + Context.Log($"perf: {Dialect} library open {cold:F0} ms cold, {warm:F0} ms warm (budget {OpenBudgetMs:F0} ms)"); + + var failures = new List(); + if (cold > OpenBudgetMs) failures.Add($"open {cold: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..328d9b64 --- /dev/null +++ b/tests/Titano.Data.Tests/Perf/RebuildPerfTests.cs @@ -0,0 +1,85 @@ +using System.Diagnostics; +using System.Text; +using Titano.Data.Archiving; +using Titano.Data.Tests.Archiving; +using Titano.Testing; + +namespace Titano.Data.Tests.Perf; + +/// +/// Phase 2 gate, §1.1 scaled: a 100,000-frame archive adopted from real files, then its index thrown away and rebuilt +/// from the sidecars alone. The rebuilt index must equal the original row for row, within a fifth of the 10-minute +/// budget §1.1 gives 500,000 photos. Opt-in: TITANO_PERF=1. +/// +[Category("perf")] +[RequiresEnvironment(PerfGate.Variable)] +[Serial] +[Timeout(3_600_000)] +public sealed class RebuildPerfTests(TestContext context) +{ + public const int Sequences = 40; + public const int FramesPerSequence = 2_500; + public const double RebuildBudgetSeconds = 600.0 * Sequences * FramesPerSequence / 500_000; + + [Test] + public async Task AHundredThousandFrameArchiveRebuildsFromSidecarsAlone() + { + await using var fx = await ArchiveFixture.CreateAsync(context); + var watch = Stopwatch.StartNew(); + Parallel.For(0, Sequences, new ParallelOptions { CancellationToken = fx.Ct }, s => + { + var start = ArchiveFixture.Start.AddDays(3 * s); + var folder = Path.Combine(fx.Paths.Root, start.Year.ToString(System.Globalization.CultureInfo.InvariantCulture), $"{start:yyyy-MM-dd} Roof {s:00}", "originals"); + Photos.WriteSeries(folder, start, FramesPerSequence, firstSeed: 1 + s * FramesPerSequence); + }); + context.Log($"perf: wrote {Sequences * FramesPerSequence:N0} photos in {watch.Elapsed.TotalSeconds:F1} s"); + + watch.Restart(); + var adopted = await fx.ScanAsync(ScanMode.Full); + context.Log($"perf: adopted {adopted.Adopted} folders in {watch.Elapsed.TotalSeconds:F1} s"); + Assert.Equal(Sequences, adopted.Adopted); + Assert.Empty(adopted.Failed); + var original = await DumpAsync(fx); + + // With the index snapshot the full scan left behind, then from the sidecar files alone (snapshot lost). + foreach (var snapshot in new[] { true, false }) + { + if (!snapshot) File.Delete(fx.Paths.SnapshotPath); + await fx.ReopenWithEmptyIndexAsync(); + watch.Restart(); + var rebuilt = await fx.ScanAsync(ScanMode.Rebuild); + var seconds = watch.Elapsed.TotalSeconds; + context.Log($"perf: 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)); + Assert.Equal(original, await DumpAsync(fx)); + Assert.Less(seconds, RebuildBudgetSeconds, "rebuild from sidecars"); + } + } + + /// Every sequence row and every frame row (paged), in folder and index order. + private static async Task DumpAsync(ArchiveFixture fx) + { + var sb = new StringBuilder(); + var frames = 0; + foreach (var location in await fx.Db.Sequences.ListLocationsAsync(fx.Archive.Id, fx.Ct)) + { + var s = (await fx.Db.Sequences.GetAsync(location.Id, fx.Ct))!; + sb.Append($"S {s.Id} {s.Folder} '{s.Title}' {s.CameraModel} {s.FirstCapture:O} {s.FrameCount} {s.TotalBytes} {s.Status} ") + .AppendLine($"{s.VerifiedAt:O} {string.Join('|', s.Tags)} {s.SettingsVersion}/{s.FramesVersion} {s.MedianInterval}"); + var after = -1; + while (true) + { + var page = await fx.Db.Frames.ListBySequenceAsync(s.Id, after, 1000, fx.Ct); + if (page.Count == 0) break; + foreach (var f in page) + { + sb.AppendLine($" F {f.Id} {f.Index} {f.RelativePath} {f.OriginalFileName} {f.Size} {f.Sha256} {f.CapturedAt:O} {f.Width}x{f.Height} {f.Format} {f.Flags}"); + frames++; + } + after = page[^1].Index; + } + } + Assert.Equal(Sequences * FramesPerSequence, frames); + return sb.ToString(); + } +} diff --git a/tests/Titano.Data.Tests/Perf/SyntheticLibrary.cs b/tests/Titano.Data.Tests/Perf/SyntheticLibrary.cs new file mode 100644 index 00000000..07bf7b23 --- /dev/null +++ b/tests/Titano.Data.Tests/Perf/SyntheticLibrary.cs @@ -0,0 +1,117 @@ +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). Deterministic for a given seed. +/// +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 => Frames(s, seed)), 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) + { + var random = new Random(HashCode.Combine(seed, sequence.Id)); + 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, + }; + } + } +} From 0f8cfd4755816a7aed98f8044c7fbaca2357f099 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 22:38:50 +0000 Subject: [PATCH 05/12] docs: architecture map, phase status, changelog and the development README ARCHITECTURE gains the module map, hosts, job kinds with their handlers, the data flow and the extension points; STATUS records the measured performance gates and the Phase 8 next steps; CHANGELOG summarises everything built under Unreleased; README covers build, tests, CI, the release process, the secrets and how to bootstrap the public releases repository. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- README.md | 119 ++++++++++++++++++++++++- docs/ARCHITECTURE.md | 205 ++++++++++++++++++++++++++++++++----------- docs/CHANGELOG.md | 85 +++++++++++++++--- docs/STATUS.md | 32 +++++-- 4 files changed, 371 insertions(+), 70 deletions(-) diff --git a/README.md b/README.md index 39227d8e..963b8d80 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,117 @@ -# 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.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, 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`); + - builds and pushes `ghcr.io//titano-server:` (and `:latest` for stable tags) for amd64 and arm64; + - computes `SHA256SUMS`, updates the public releases repository and creates (or updates) the GitHub release there. +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`. Builds embed it through the `TitanoReleasesRepo` MSBuild property (default `alby96/titano-releases`), so keep the two in line. | +| `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; 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, rewriting links to its name, then + creates the release with the installers. +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/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 8a51336d..e790a519 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -1,83 +1,182 @@ # 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`); 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 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, filters < 200 ms) on SQLite and PostgreSQL, and the 100,000-frame + rebuild from sidecars. `.github/workflows/perf.yml` runs them weekly against PostgreSQL 17. -## 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 +184,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..e7898c29 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -1,17 +1,82 @@ # 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 is fetched into + `%TEMP%\Titano\updates`, verified against the release's `SHA256SUMS` and shown in Explorer. +- 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 on SQLite and PostgreSQL 17, 100,000-frame rebuild + from sidecars. + +### 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. diff --git a/docs/STATUS.md b/docs/STATUS.md index 8ae31a7c..d9464e4b 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 rebuilds from sidecars into the identical index in 1.1 s (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 313 ms cold on SQLite, 162 ms on PostgreSQL (budget 1 s); every filter, search, sort and next page ≤ 8.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 › *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 + appears in Explorer. + +## 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. From b41755f326154604939ba77f4454989d7a959d2f Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 22:43:29 +0000 Subject: [PATCH 06/12] test(perf): say which parts of the synthetic library follow the seed Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- tests/Titano.Data.Tests/Perf/SyntheticLibrary.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/Titano.Data.Tests/Perf/SyntheticLibrary.cs b/tests/Titano.Data.Tests/Perf/SyntheticLibrary.cs index 07bf7b23..aa1c286f 100644 --- a/tests/Titano.Data.Tests/Perf/SyntheticLibrary.cs +++ b/tests/Titano.Data.Tests/Perf/SyntheticLibrary.cs @@ -7,7 +7,8 @@ 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). Deterministic for a given seed. +/// mixed status flags, written straight into the index (no files). Titles, cameras, dates, tags and flags follow the +/// seed; ids and hashes are random. /// internal static class SyntheticLibrary { From aac253927606ecbad1fb01d9d0fcdd43a4381289 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 23:12:32 +0000 Subject: [PATCH 07/12] ci(release): valid bug form, YAML check, embed the releases repository, keep public content on the newest release - Quote the bug form's Version description (it did not parse, so GitHub offered no bug form at all). - .github/scripts/check-yaml.rb parses workflows, the compose file and the public issue forms (and checks the form shape); CI runs it on Linux and the release job runs it before publishing the forms. - Builds and publishes pass TitanoReleasesRepo=$RELEASES_REPO, so binaries read the repository they are published to. - Image links in the public repository point to the image the docker job pushed. - The public repository content follows the newest stable release; older tags and pre-releases only get their release, and an older stable tag is never marked Latest. - Screenshot captures time out after 10 minutes; the perf summary reports missing timings. - Public README names the in-app "Suggest a fix" link. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- .github/scripts/check-yaml.rb | 42 ++++++++++++++++ .github/workflows/ci.yml | 6 +++ .github/workflows/perf.yml | 6 ++- .github/workflows/release.yml | 49 ++++++++++++++----- README.md | 9 ++-- .../.github/ISSUE_TEMPLATE/bug_report.yml | 2 +- deploy/releases-repo/README.md | 2 +- 7 files changed, 99 insertions(+), 17 deletions(-) create mode 100644 .github/scripts/check-yaml.rb 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 e5a00411..8df564be 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -64,6 +64,11 @@ 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 run: dotnet "$TOOLS" fixtures --allow-missing @@ -87,6 +92,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 index 5e43f70b..0a8f0e75 100644 --- a/.github/workflows/perf.yml +++ b/.github/workflows/perf.yml @@ -58,7 +58,11 @@ jobs: { echo "## Performance gates" echo '```' - grep -h "perf:" out-perf.log 2>/dev/null | sed 's/^ *//' || echo "no timings recorded" + 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" diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 24222a51..08d0e962 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -24,7 +24,8 @@ env: DOTNET_NOLOGO: "1" DOTNET_CLI_TELEMETRY_OPTOUT: "1" 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. + # 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: @@ -71,13 +72,14 @@ jobs: - name: Build and test run: | - dotnet build Titano.slnx -c Release -p:TitanoVersion="$VERSION" + dotnet build Titano.slnx -c Release -p:TitanoVersion="$VERSION" -p:TitanoReleasesRepo="$RELEASES_REPO" for t in Core Data Server 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 & @@ -87,7 +89,7 @@ jobs: - 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 @@ -232,20 +234,41 @@ jobs: - 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 - echo "repo=$RELEASES_REPO" >> "$GITHUB_OUTPUT" + repo="$RELEASES_REPO" else - echo "repo=$GITHUB_REPOSITORY" >> "$GITHUB_OUTPUT" + 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) follows the newest stable release, so re-publishing an + # older tag or publishing a pre-release never rolls it back; until a stable release exists, every tag updates it. + 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 is left as it is." + 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: Update the public releases repository - if: env.HAS_RELEASES_TOKEN == 'true' + if: env.HAS_RELEASES_TOKEN == 'true' && steps.target.outputs.newest == 'true' env: GH_TOKEN: ${{ secrets.RELEASES_TOKEN }} run: | - owner="${RELEASES_REPO%%/*}" 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" @@ -261,9 +284,9 @@ jobs: 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 image owner. + # 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#${RELEASES_REPO}#g" -e "s#ghcr.io/alby96/#ghcr.io/${owner,,}/#g" + xargs -0 -r sed -i -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" @@ -279,12 +302,16 @@ jobs: 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" + 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" + gh release create "$TAG" out/release/* --repo "$TARGET" --title "Titano $VERSION" --notes-file out/release-notes.md --prerelease="$PRERELEASE" "${latest[@]}" fi - name: Summary diff --git a/README.md b/README.md index 963b8d80..f5e94288 100644 --- a/README.md +++ b/README.md @@ -58,7 +58,7 @@ The server reads `/data/server.json` (`TITANO_DATA_PATH`) and `TITANO_*` environ | 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, 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/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) | @@ -75,7 +75,10 @@ The server reads `/data/server.json` (`TITANO_DATA_PATH`) and `TITANO_*` environ 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`); - builds and pushes `ghcr.io//titano-server:` (and `:latest` for stable tags) for amd64 and arm64; - - computes `SHA256SUMS`, updates the public releases repository and creates (or updates) the GitHub release there. + - computes `SHA256SUMS`, checks the public issue forms, updates the public releases repository and creates (or + updates) the GitHub release there. The repository content (README, EULA, `i18n/`, `SHA256SUMS`) follows the + newest stable release: a pre-release, or an older tag published again, only gets its release and never becomes + *Latest*. 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 @@ -83,7 +86,7 @@ The server reads `/data/server.json` (`TITANO_DATA_PATH`) and `TITANO_*` environ | 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`. Builds embed it through the `TitanoReleasesRepo` MSBuild property (default `alby96/titano-releases`), so keep the two in line. | +| `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`. | diff --git a/deploy/releases-repo/.github/ISSUE_TEMPLATE/bug_report.yml b/deploy/releases-repo/.github/ISSUE_TEMPLATE/bug_report.yml index 724a373f..7744468d 100644 --- a/deploy/releases-repo/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/deploy/releases-repo/.github/ISSUE_TEMPLATE/bug_report.yml @@ -23,7 +23,7 @@ body: id: version attributes: label: Version - description: About shows it (server: admin panel › About, or /api/v1/server/info). + description: "About shows it (server: admin panel › About, or /api/v1/server/info)." placeholder: "0.2.0" validations: required: true diff --git a/deploy/releases-repo/README.md b/deploy/releases-repo/README.md index d56c0f72..0d0414ea 100644 --- a/deploy/releases-repo/README.md +++ b/deploy/releases-repo/README.md @@ -100,7 +100,7 @@ Run `Titano.Server.exe` in a console, or install it as a Windows service from an 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 *Review* link in About, which leads here. +your proposal — or the in-app *Suggest a fix* link in About, which leads here. ## Verifying downloads From ffa05d9f69bf20a5bbef8436fd382ac2dda8ab2f Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 3 Oct 2026 10:00:54 +0000 Subject: [PATCH 08/12] fix(app): resumable, cancellable update download; portable copies get the portable zip - UpdateFlow owns the update notice (check, download, cancel) as a plain class; AboutViewModel only maps it to text and commands. - A portable copy downloads and verifies Titano-win-x64-portable-.zip instead of the setup; a release without the package or SHA256SUMS opens its page. - The download fails after 60 s without data instead of after 30 minutes, keeps its .part file and resumes it with a range request; Cancel stops it. - Older release folders under %TEMP%\Titano\updates are removed after a verified download; an unexpected exception never leaves "Downloading". - Tooltips show the package size; stale machine translations of the three rewritten tooltips are removed so they fall back to English. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- i18n/ar/Tooltips.ar.resx | 3 - i18n/cs/Tooltips.cs.resx | 3 - i18n/da/Tooltips.da.resx | 3 - i18n/de/Tooltips.de.resx | 3 - i18n/el/Tooltips.el.resx | 2 - i18n/en/About.resx | 3 +- i18n/en/Tooltips.resx | 6 +- i18n/es/Tooltips.es.resx | 3 - i18n/et/Tooltips.et.resx | 3 - i18n/fi/Tooltips.fi.resx | 3 - i18n/fr/Tooltips.fr.resx | 3 - i18n/he/Tooltips.he.resx | 3 - i18n/hi/Tooltips.hi.resx | 3 - i18n/it/About.it.resx | 3 +- i18n/it/Tooltips.it.resx | 6 +- i18n/ja/Tooltips.ja.resx | 3 - i18n/ko/Tooltips.ko.resx | 3 - i18n/nb/Tooltips.nb.resx | 3 - i18n/nl/Tooltips.nl.resx | 3 - i18n/pl/Tooltips.pl.resx | 3 - i18n/pt-BR/Tooltips.pt-BR.resx | 3 - i18n/pt-PT/Tooltips.pt-PT.resx | 3 - i18n/ru/Tooltips.ru.resx | 3 - i18n/sv/Tooltips.sv.resx | 3 - i18n/tr/Tooltips.tr.resx | 3 - i18n/uk/Tooltips.uk.resx | 3 - i18n/zh-Hans/Tooltips.zh-Hans.resx | 3 - i18n/zh-Hant/Tooltips.zh-Hant.resx | 3 - src/Titano.App/About/UpdateDownload.cs | 180 ++++++++--- src/Titano.App/About/UpdateFlow.cs | 177 +++++++++++ src/Titano.App/Infrastructure/AppServices.cs | 9 +- src/Titano.App/Sections/AboutView.xaml | 11 +- src/Titano.App/Sections/AboutViewModel.cs | 156 +++------- src/Titano.App/Sections/SettingsView.xaml | 9 +- .../About/UpdateDownloadTests.cs | 287 ++++++++++++++---- .../Titano.App.Tests/About/UpdateFlowTests.cs | 208 +++++++++++++ 36 files changed, 828 insertions(+), 298 deletions(-) create mode 100644 src/Titano.App/About/UpdateFlow.cs create mode 100644 tests/Titano.App.Tests/About/UpdateFlowTests.cs 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/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 a5f9d563..1b135fae 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, σε φάκελο της επιλογής σας. Οι ρυθμίσεις και οι κωδικοί πρόσβασης δεν περιλαμβάνονται - Άνοιγμα της σελίδας της έκδοσης στο πρόγραμμα περιήγησης Άνοιγμα της άδειας χρήσης στο πρόγραμμα περιήγησης Άνοιγμα του φακέλου με τη βάση δεδομένων, τις ρυθμίσεις και τα αρχεία καταγραφής Άνοιγμα της δημόσιας σελίδας εκδόσεων στο πρόγραμμα περιήγησης diff --git a/i18n/en/About.resx b/i18n/en/About.resx index 1dc68f3f..37466cd9 100644 --- a/i18n/en/About.resx +++ b/i18n/en/About.resx @@ -19,6 +19,7 @@ None Translation Titano {0} available + Cancel Check for updates Checking… Up to date @@ -28,6 +29,6 @@ Check failed Download not verified Titano {0} downloaded - Show setup + Show file Updates diff --git a/i18n/en/Tooltips.resx b/i18n/en/Tooltips.resx index 5b582eb1..6ece7aea 100644 --- a/i18n/en/Tooltips.resx +++ b/i18n/en/Tooltips.resx @@ -4,13 +4,17 @@ 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, 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 · tens of MB + 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 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/it/About.it.resx b/i18n/it/About.it.resx index 2f871e07..c290af5d 100644 --- a/i18n/it/About.it.resx +++ b/i18n/it/About.it.resx @@ -19,6 +19,7 @@ Nessuno Traduzione Titano {0} disponibile + Annulla Cerca aggiornamenti Verifica in corso… Aggiornato @@ -28,6 +29,6 @@ Verifica non riuscita Download non verificato Titano {0} scaricato - Mostra installer + Mostra file Aggiornamenti diff --git a/i18n/it/Tooltips.it.resx b/i18n/it/Tooltips.it.resx index 313730a4..4246176c 100644 --- a/i18n/it/Tooltips.it.resx +++ b/i18n/it/Tooltips.it.resx @@ -4,13 +4,17 @@ 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 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 · decine di MB + 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 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/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/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/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/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/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/UpdateDownload.cs b/src/Titano.App/About/UpdateDownload.cs index 7fade974..0797b554 100644 --- a/src/Titano.App/About/UpdateDownload.cs +++ b/src/Titano.App/About/UpdateDownload.cs @@ -1,5 +1,7 @@ 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; @@ -10,31 +12,47 @@ namespace Titano.App.About; public sealed class UpdateVerificationException(string message) : Exception(message); /// -/// "Download" of the update notice (BRIEF §18, P1): fetches the desktop setup of the latest release 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 it. +/// "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 desktop setup ("Titano-Setup-1.2.3.exe"), not the Uploader's. - public static ReleaseAsset? Installer(ReleaseInfo release) => - release.Assets.FirstOrDefault(a => a.Name.StartsWith("Titano-Setup-", StringComparison.OrdinalIgnoreCase) - && a.Name.EndsWith(".exe", StringComparison.OrdinalIgnoreCase) - && a.Name == Path.GetFileName(a.Name)); + /// + /// 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 a setup and SHA256SUMS; otherwise only its page can be opened. - public static bool CanDownload(ReleaseInfo release) => Installer(release) is not null && Checksums(release) is not null; + /// 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\<tag> under . - public static string Folder(string tempRoot, ReleaseInfo release) => - Path.Combine(tempRoot, "Titano", "updates", string.Concat(release.Tag.Select(c => char.IsAsciiLetterOrDigit(c) || c is '.' or '-' ? c : '_'))); + /// %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 @@ -55,80 +73,134 @@ public static class UpdateDownload } /// - /// Downloads the setup of into , verifies it against - /// SHA256SUMS and returns its path. A verified copy already there is reused; a partial or mismatching - /// download is deleted. + /// 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. - public static async Task DownloadAsync(HttpClient http, ReleaseInfo release, string folder, string userAgentVersion, IProgress? progress, - CancellationToken ct) + /// 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 installer = Installer(release) ?? throw new UpdateVerificationException($"Release {release.Tag} has no Titano setup."); + 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 expected = ParseChecksums(await ReadChecksumsAsync(http, checksums, userAgentVersion, ct).ConfigureAwait(false)).GetValueOrDefault(installer.Name) - ?? throw new UpdateVerificationException($"{ChecksumsName} of {release.Tag} has no line for {installer.Name}."); + 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, installer.Name); + 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 + ".part"; - try - { - var actual = await DownloadToAsync(http, installer, part, userAgentVersion, progress, ct).ConfigureAwait(false); - if (actual != expected) throw new UpdateVerificationException($"{installer.Name}: SHA-256 {actual} does not match {expected} in {ChecksumsName}."); - File.Move(part, target, overwrite: true); - return target; - } - finally + 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, ct).ConfigureAwait(false); + 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 , hashing as it goes; refuses more bytes than the release announced. + /// + /// 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, - CancellationToken ct) + CancellationTokenSource idle, TimeSpan idleTimeout) { - using var response = await SendAsync(http, asset, userAgentVersion, ct).ConfigureAwait(false); - var length = asset.Size > 0 ? asset.Size : response.Content.Headers.ContentLength ?? -1; - await using var input = await response.Content.ReadAsStreamAsync(ct).ConfigureAwait(false); - await using var output = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, 1 << 16, FileOptions.Asynchronous); + 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) throw new UpdateVerificationException($"{asset.Name} is larger than the release announced."); + 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 (length > 0) progress?.Report(Math.Min(1.0, (double)total / length)); + 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, CancellationToken ct) + 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 { @@ -142,18 +214,32 @@ public static class UpdateDownload } } + /// 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 (IOException) - { - // A scanner may hold the partial file; %TEMP% cleanup removes it later. - } - catch (UnauthorizedAccessException) + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { + // A scanner may hold the file; the next download overwrites it. } } 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 d6dc5a8d..4744f842 100644 --- a/src/Titano.App/Infrastructure/AppServices.cs +++ b/src/Titano.App/Infrastructure/AppServices.cs @@ -39,8 +39,8 @@ public sealed class AppServices : IAsyncDisposable private static readonly Lazy Http = new(() => new HttpClient { Timeout = TimeSpan.FromSeconds(20) }); - /// Setups are large: the download is bounded by the caller's cancellation, not a short timeout. - private static readonly Lazy DownloadHttp = new(() => new HttpClient { Timeout = TimeSpan.FromMinutes(30) }); + /// 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; @@ -59,7 +59,8 @@ public sealed class AppServices : IAsyncDisposable Encoders = new MediaFoundationInventory(); CheckForUpdateAsync = ct => UpdateCheck.FetchAsync(Http.Value, ProductLinks.LatestReleaseApi, VersionText, ct); DownloadUpdateAsync = (release, progress, ct) => - UpdateDownload.DownloadAsync(DownloadHttp.Value, release, UpdateDownload.Folder(Path.GetTempPath(), release), VersionText, progress, ct); + UpdateDownload.DownloadAsync(DownloadHttp.Value, release, environment.IsPortable, UpdateDownload.Root(Path.GetTempPath()), VersionText, progress, + UpdateDownload.IdleTimeout, ct); } public AppEnvironment Environment { get; } @@ -94,7 +95,7 @@ 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 setup of a release (BRIEF §18 P1) and returns its path. + /// 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. diff --git a/src/Titano.App/Sections/AboutView.xaml b/src/Titano.App/Sections/AboutView.xaml index 7b445788..805a251a 100644 --- a/src/Titano.App/Sections/AboutView.xaml +++ b/src/Titano.App/Sections/AboutView.xaml @@ -55,11 +55,14 @@