From 87d7a3a36da16001488412f4a15a5ff46f68ce12 Mon Sep 17 00:00:00 2001 From: lzy98276 Date: Sat, 14 Nov 2026 19:21:32 +0800 Subject: [PATCH 01/26] =?UTF-8?q?refactor:=20=E7=A7=BB=E9=99=A4=E4=BA=91?= =?UTF-8?q?=E5=A4=87=E4=BB=BD=E3=80=81=E8=AF=81=E6=98=8E=E9=93=BE=E4=B8=8E?= =?UTF-8?q?=E9=85=8D=E7=BD=AE=E9=98=B2=E7=AF=A1=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 云备份:删除 CloudBackupService/CloudAutomaticBackupService/SectlCloudStorageClient/CloudBackupPackage 及备份页云 tab、云配置项与相关本地化;ArchiveKind.CloudBackup 仅保留为旧值,旧云包导入直接拒绝 - 证明链:删除 DrawProof.Chain/DrawProofChain、ProofChainStore、ProofIntegrityVerifier 与验证页链校验入口;证明文件保留为普通 OfflineReproducible 文档,服务端回执计算从未包含链字段,旧回执继续有效 - 配置防篡改:删除 SettingsIntegrityService/RecoveryService/CommandGate、App 启动闸门与 IPC/URL 分支、SecuritySettingsConfig 三个开关及安全页设置项与本地化;凭据 FormatVersion/AAD 未动 - 同步改写根、SecRandom、SecRandom.Core、SettingsPages 四份 AGENTS.md 涉及删除的测试:ProofChainTests、SettingsIntegrity*Tests、CloudBackup*Tests、SectlCloudStorageClientTests;DataArchiveServiceTests 增加旧云包拒绝用例 --- AGENTS.md | 17 +- SecRandom.Core.Tests/BackupConfigTests.cs | 33 +- .../CloudBackupPackageTests.cs | 306 -------- .../CloudBackupServiceTests.cs | 715 ------------------ .../DataArchiveServiceTests.cs | 190 +---- .../DrawProofAttestationQueueTests.cs | 32 +- .../PluginDrawServiceTests.cs | 24 +- SecRandom.Core.Tests/ProofChainTests.cs | 253 ------- .../SectlCloudStorageClientTests.cs | 276 ------- .../SettingsIntegrityCommandGateTests.cs | 32 - .../SettingsIntegrityRecoveryServiceTests.cs | 335 -------- .../SettingsIntegrityServiceTests.cs | 203 ----- .../UserFeedbackServiceTests.cs | 4 - SecRandom.Core/AGENTS.md | 6 +- .../Enums/Configs/SettingsIntegrityAction.cs | 13 - .../Configs/SettingsIntegrityRestoreSource.cs | 16 - .../Models/SubConfigs/General/BackupConfig.cs | 32 - .../SubConfigs/SecuritySettingsConfig.cs | 18 - .../Services/Archive/CloudBackupPackage.cs | 411 ---------- .../Services/Archive/DataArchiveService.cs | 99 +-- .../ControlNode/ControlSettingsLabels.cs | 23 +- .../Models/Verification/DrawProof.cs | 26 - SecRandom/AGENTS.md | 26 +- SecRandom/App.axaml.cs | 598 ++++++++------- .../General/Backup/Resources.Designer.cs | 639 ---------------- .../General/Backup/Resources.en-US.resx | 2 +- .../General/Backup/Resources.ja-JP.resx | 2 +- .../General/Backup/Resources.resx | 284 ++----- .../Verification/Resources.Designer.cs | 16 - .../General/Verification/Resources.en-US.resx | 6 +- .../General/Verification/Resources.ja-JP.resx | 6 +- .../General/Verification/Resources.resx | 36 +- .../Security/Resources.Security.cs | 29 - .../Security/Resources.en-US.resx | 31 +- .../Security/Resources.ja-JP.resx | 31 +- .../SettingsPages/Security/Resources.resx | 31 +- SecRandom/Models/CloudBackupMetadata.cs | 20 - .../Services/Auth/SectlCloudStorageClient.cs | 325 -------- .../CloudAutomaticBackupService.cs | 79 -- .../ImportExport/CloudBackupService.cs | 456 ----------- .../ImportExport/IImportExportService.cs | 5 - .../ImportExport/ImportExportService.cs | 27 +- .../Security/SecurityCredentialStore.cs | 27 +- .../Services/Security/SecurityService.cs | 24 +- .../Security/SecuritySettingsStore.cs | 3 - .../Security/SettingsIntegrityCommandGate.cs | 16 - .../SettingsIntegrityRecoveryService.cs | 460 ----------- .../Security/SettingsIntegrityService.cs | 155 ---- .../DrawProofAttestationService.cs | 28 +- .../Verification/DrawProofExportService.cs | 41 +- .../Services/Verification/ProofChainStore.cs | 238 ------ .../Verification/ProofIntegrityVerifier.cs | 198 ----- .../VerificationDrawCoordinator.cs | 6 +- .../Services/Verification/WitnessClient.cs | 2 +- .../Services/Verification/WitnessContracts.cs | 28 +- SecRandom/Views/SettingsPages/AGENTS.md | 16 +- .../General/BackupSettingsPage.axaml | 451 +++-------- .../General/BackupSettingsPage.axaml.cs | 639 +--------------- .../General/SecuritySettingsPage.axaml | 42 +- .../General/SecuritySettingsPage.axaml.cs | 72 +- .../General/VerificationSettingsPage.axaml | 17 - .../General/VerificationSettingsPage.axaml.cs | 57 -- 62 files changed, 668 insertions(+), 7565 deletions(-) delete mode 100644 SecRandom.Core.Tests/CloudBackupPackageTests.cs delete mode 100644 SecRandom.Core.Tests/CloudBackupServiceTests.cs delete mode 100644 SecRandom.Core.Tests/ProofChainTests.cs delete mode 100644 SecRandom.Core.Tests/SectlCloudStorageClientTests.cs delete mode 100644 SecRandom.Core.Tests/SettingsIntegrityCommandGateTests.cs delete mode 100644 SecRandom.Core.Tests/SettingsIntegrityRecoveryServiceTests.cs delete mode 100644 SecRandom.Core.Tests/SettingsIntegrityServiceTests.cs delete mode 100644 SecRandom.Core/Enums/Configs/SettingsIntegrityAction.cs delete mode 100644 SecRandom.Core/Enums/Configs/SettingsIntegrityRestoreSource.cs delete mode 100644 SecRandom.Core/Services/Archive/CloudBackupPackage.cs delete mode 100644 SecRandom/Models/CloudBackupMetadata.cs delete mode 100644 SecRandom/Services/Auth/SectlCloudStorageClient.cs delete mode 100644 SecRandom/Services/ImportExport/CloudAutomaticBackupService.cs delete mode 100644 SecRandom/Services/ImportExport/CloudBackupService.cs delete mode 100644 SecRandom/Services/Security/SettingsIntegrityCommandGate.cs delete mode 100644 SecRandom/Services/Security/SettingsIntegrityRecoveryService.cs delete mode 100644 SecRandom/Services/Security/SettingsIntegrityService.cs delete mode 100644 SecRandom/Services/Verification/ProofChainStore.cs delete mode 100644 SecRandom/Services/Verification/ProofIntegrityVerifier.cs diff --git a/AGENTS.md b/AGENTS.md index eec8c4e9b..acccc11de 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -82,7 +82,6 @@ Nested instruction files: | Fair draw logic | `SecRandom.Core/Services/Draw/` | Partial `DrawEngine`, weighted draw, filters, crypto RNG, plus `DrawCommitCoordinator` (`IDrawCommitService`) transactional commits and shared `DrawRepeatPolicy`/`DrawCandidateFilter`. | | History record groups (历史记录组) | `SecRandom.Core/Services/Profiles/HistoryGroupCatalog.cs`, `HistoryGroupName.cs`, `SecRandom/ViewModels/MainPages/{RollCall,Lottery}PageViewModel.cs`, `SecRandom/Views/SettingsPages/Picking/DefaultDrawSettingsPage.axaml(.cs)` | Optional per-purposes split of the same profile history: a draw can be locked to one record group so weights only read that group's records and new records land in it. `HistoryItem.HistoryGroup` (empty = default group) is orthogonal to `CourseName`, so the two filters intersect; `StudentHistory`/`PrizeHistory` keep the registered group list in `HistoryGroups`, and the group *selection* on a main page is transient UI state that is never persisted (a page starts from the persisted default record group — `RollCallSettingsConfig.HistoryGroup` / `LotterySettingsConfig.HistoryGroup`, empty = 默认记录组 — and then only the visible `ComboBox` changes during that session, so a stale selection can never silently keep filtering); hiding the selector always means "no group scope" (`null`). The configuration value and the runtime scope are separated by `HistoryGroupScope.Resolve` (`SecRandom.Core/Services/Profiles/HistoryGroupScope.cs`): feature off ⇒ `null`, blank ⇒ `""` (默认记录组), an existing name ⇒ that name, a deleted/renamed name ⇒ `""` plus a "原组已不存在" hint (deletion only moves records back to the default group), and an unreadable catalogue ⇒ `null` rather than narrowing weights to an unverifiable group. Off by default (`General.HistoryGroups.Enabled`), readable-but-not-writable through the control plane, and deliberately not a protected operation. | | Config persistence | `SecRandom.Core/Services/Config/`, `SecRandom.Core/Services/HistoryStore/` | `FileConfigService` and handlers are host-internal Core runtime services; desktop keeps its existing package-root data path. v3 backup/archive transfer lives in `SecRandom.Core/Services/Archive/` (`DataArchiveService`). **Profile history is the one exception to JSON**: each list/pool history is a small SQLite database (`data/history/{roll_call_history,lottery_history}/{name}.srhdb`) read and written by `ProfileHistoryDatabase`, because a history file grows without bound while the JSON handler rewrote the whole file on every save (three times per draw). `StudentHistoryConfig`/`PrizeHistoryConfig` only override the `ConfigHandlerBase` storage seams (`LoadData`/`SaveData`/`DeleteData`); every path decision (exists / enumerate / rename / delete) must go through `ProfileHistoryPaths`, never a hand-built `{name}.json`. Saves are incremental — each record row carries a content fingerprint (`row_hash`), so a draw only writes the changed member plus its new rows. The switch is transparent: the first read of a profile imports its legacy `{name}.json` into the database and renames it to `{name}.json.migrated`, which no `*.json` reader matches, so archives stay readable and the old file survives as a one-time rollback copy. | -| Account cloud backup | `SecRandom/Services/ImportExport/CloudBackupService.cs`, `SecRandom/Services/ImportExport/CloudAutomaticBackupService.cs`, `SecRandom/Services/Auth/SectlCloudStorageClient.cs`, `SecRandom.Core/Services/Archive/CloudBackupPackage.cs` | Desktop and mobile account cloud sync over the SECTL personal cloud API: `CloudBackup` archives split into verified parts plus a trailing manifest, cloud listing/delete, and verified download before the normal v3 restore. Every upload carries a device alias (`BackupConfig.CloudDeviceAlias`; when empty, the mobile heads' device label — Android/iOS report `localhost` as their host name — and otherwise the host name) that labels the cloud list and scopes retention per device. `CloudAutomaticBackupService` is the hosted service behind the separate `BackupConfig.CloudAutoBackup*` cadence and retention settings. Cloud backups are uploaded as the plain v3 archive: there is deliberately no client-side encryption and no passphrase, so account access is the only key and any signed-in device can restore every backup. | | Audit tooling | `scripts/FairnessAudit/` | Standalone fairness/performance validation script and HTML report generator. | | Release history dataset | `scripts/ReleaseHistory/`, `docs/release-history/` | Multi-sheet XLSX over GitHub Releases + `CHANGELOG/` + local git: version timeline, per-release highlights, adjacent-version deltas, removed/downgraded features, contributors, star growth, asset download counts. Refresh with `powershell -File scripts/ReleaseHistory/update-release-history.ps1`, then `verify_workbook.py`. Star timelines need a logged-in `gh` CLI; manual conclusions live in `docs/release-history/curated/annotations.json`. | | Release update signing | `scripts/ReleaseManifest/`, `scripts/validate-release-metadata.ps1`, `.github/workflows/build_publish.yml`, `.github/workflows/build_ios.yml` | Ed25519 key-generation helper and CI manifest signer; private key is Actions-secret-only. Release intermediates and final artifacts are grouped under `artifacts/release/`. The channel gate validates `metadata.yaml` against the release tag before every build. iOS builds out of band and then attaches the IPA, a re-signed manifest, and a refreshed release note to the release the publish job created (`scripts/ReleaseManifest/Update-ReleaseManifest.ps1`). | @@ -135,9 +134,6 @@ Keep this map short and stable. When code moves, AI agents should re-read the mo | `LoopbackAuthCallbackPage` | app renderer | `SecRandom/Services/Auth/LoopbackAuthCallbackPage.cs` | The one browser page the desktop loopback broker answers the OAuth redirect with: a self-contained document (inline CSS, inline 96×96 app icon as base64, no script, no second request) whose light/dark follows the **browser** through `prefers-color-scheme`, because it is not an Avalonia window and cannot read the in-app theme. Its copy lives in `SecRandom/Langs/Auth/` (three languages, `C_` keys) and says "back in SecRandom", never "signed in": `SectlAuthService` writes this response *before* it validates `state` and exchanges the code. Only a short lowercase `error` code is echoed, and only on the failure state. | | `SectlHeartbeatService` | hosted app service | `SecRandom/Services/Auth/SectlHeartbeatService.cs` | OAuth device heartbeat for desktop and mobile: reports immediately for a signed-in session and then every five minutes. | | `SectlCloudStorageClient` | app service | `SecRandom/Services/Auth/SectlCloudStorageClient.cs` | Typed client for the SECTL personal cloud API (`/api/cloud/*`): platform-scoped listing, base64 upload, short-lived download URLs, delete, and quota, with service error codes preserved. | -| `CloudBackupService` | app service | `SecRandom/Services/ImportExport/CloudBackupService.cs` | Account cloud-sync orchestration: packages a `CloudBackup` archive, uploads verified parts plus a trailing manifest, lists/groups cloud backups, verifies and rebuilds a download, deletes parts before the manifest, and purges incomplete backups. Every upload stamps this device's alias into the backup id, retention keeps only this device's own surplus, and `UploadAutomaticAsync` is the only path that frees account space. It uploads the archive as produced — client-side encryption was removed, so account access is the only key — and exposes `DeviceTag`/`IsOwnBackup` so a consumer can tell this device's backups from another machine's. A package the removed feature uploaded keeps its `IsEncrypted` name marker: it stays listed (and deletable) but `CanRestore` is false, because this build holds no way to derive its key. | -| `CloudAutomaticBackupService` | hosted app service | `SecRandom/Services/ImportExport/CloudAutomaticBackupService.cs` | Automatic cloud backup on the `BackupConfig.CloudAutoBackup*` cadence, on desktop and mobile; follows this device's own newest cloud upload and keeps each signed-in device inside its own retention limit, while an exhausted quota still removes the account-wide oldest backup. | -| `CloudBackupPackage` | domain helper | `SecRandom.Core/Services/Archive/CloudBackupPackage.cs` | Cloud backup part/manifest format: file naming, backup-id generation with the optional device alias, backup-id safety and alias parsing, splitting, manifest validation, and per-part plus whole-archive SHA-256 merging. Schema 1 is the only supported version: the parts carry the v3 ZIP archive itself. The removed feature's `-enc` name marker is still parsed so a schema-2 package from an older build is recognised and refused (its manifest is rejected by the schema check) instead of being mis-grouped as a current backup. | | `PlatformUsageReportService` | app service | `SecRandom/Services/PlatformUsageReportService.cs` | Hosted reporter for the SECTL usage counters (`daily_roll_call_count` family); counts draws after a successful commit and app launches at startup, gated by `OnlineStatusMode`, and posts through the aggregate reporting entrance `PlatformStatsApi.ReportUri`. | | `UsageMetricCounter` | domain helper | `SecRandom.Core/Services/Stats/UsageMetricCounter.cs` | Pure current-local-day event counters plus the pinned `platform_id`/`field_key`/`delta` increment payload shape (no time field: the service stamps receive time; no `value`, which would be judged as a last-value field report). | | `PlatformVersionReportService` | hosted app service | `SecRandom/Services/PlatformVersionReportService.cs` | Hosted version-usage reporter: one best-effort report per start carrying the build version plus the device UUID only, posted to the aggregate reporting entrance (where `version` is what makes it a version report), run on the thread pool so startup is never delayed, and deliberately not gated by `OnlineStatusMode`. | @@ -159,16 +155,15 @@ Keep this map short and stable. When code moves, AI agents should re-read the mo - All SECTL statistics reporting goes through the one aggregate entrance `PlatformStatsApi.ReportUri` (`POST /api/stats/report`), never a per-type endpoint: the four old endpoints (`/api/stats/online`, `/api/stats/usage/increment`, `/api/stats/version`, `/api/fields/values`) are compatibility-only and must not be reintroduced. The service judges the report type from the payload keys and stops at the first hit — (1) `field_key` **and** `value` → field, (2) `version`/`app_version` → version, (3) `metrics`/`increments`/`usage`/`delta`/`metric_key` → usage, (4) anything else carrying `platform_id`/`device_uuid` → online — and answers `400` when nothing matches. That judgment is why the payload shapes are load-bearing rather than cosmetic: posting the right fields to the wrong old endpoint, or adding a field of an earlier rule (a `value` in an increment, a `version` in a heartbeat), does not fail, it silently books the number under another figure. Keep `PlatformStatsReportEntranceTests` matching the documented order if the API's rule ever changes. - Telemetry access is seam-based: runtime code depends on `ITelemetryTransaction` / `ITelemetrySdkAdapter` and must not reference Sentry types directly (the DSN lives in `GlobalConstants.SentryDsn`). `TelemetryRuntimeService` is Sentry-free; the desktop-only `TelemetryTransactionSentryExtensions` shim is excluded from mobile builds, while mobile links the same telemetry sources, adds `MobileProfilingIntegrationStub`, and owns its Sentry DI/init/shutdown plus Android/iOS unhandled-exception hooks. - The pseudo-anonymous device UUID belongs in `data/config/device-uuid.json`; legacy settings values are migration-only and must not be serialized back into `settings.json`. Full-data and configuration backups include this file, while settings-only exports do not overwrite a device identity. -- ClassIsland notifications require the installed `SecRandom4Ci` v2 plugin. `NotificationService` uses the local `SecRandom4Ci.Interface` contract and `ClassIsland.IPC.v2.Server`; it must not use loopback TCP. SecRandom's built-in notification channel is the existing QuickDraw result window, shared by roll-call, QuickDraw, and lottery notifications. Each draw channel only controls whether it is enabled; `NotificationSettings.Default` owns the one global service, duration, threshold, fallback, and built-in auto-close configuration. `UseBuiltInOnServiceFailure` is the backend-neutral fallback policy for a selected external notification service and defaults to enabled; current ClassIsland-only delivery uses it when v2 IPC fails. For automatic QuickDraw delivery, the built-in or dual service opens this window before the draw to show the rolling animation and then its result; external-only delivery must not open the QuickDraw window unless the fallback runs. Notification settings must not duplicate the QuickDraw window's placement, opacity, or draw-animation controls. +- ClassIsland notifications require the installed `SecRandom4Ci` v2 plugin. `NotificationService` uses the local `SecRandom4Ci.Interface` contract and `ClassIsland.IPC.v2.Server`; it must not use loopback TCP. SecRandom's built-in notification channel is the existing QuickDraw result window, shared by roll-call, QuickDraw, and lottery notifications. Each draw channel only controls whether it is enabled; `NotificationSettings.Default` owns the one global service, duration, threshold, fallback, and built-in auto-close configuration. `UseBuiltInOnServiceFailure` is the backend-neutral fallback policy for a selected external notification service and defaults to enabled; current ClassIsland-only delivery uses it when v2 IPC fails. For automatic QuickDraw delivery, the built-in or dual service opens this window before the draw to show the rolling animation and then its result; external-only delivery must not open the QuickDraw window unless the fallback runs. Notification settings must not duplicate the QuickDraw window's draw-animation controls. The built-in notification floating window's geometry — position, monitor, horizontal/vertical offset, and opacity — is global, edited only on the separate `settings.notification.floatingWindow` page (`NotificationFloatingWindowSettingsPage`, registered directly above `settings.notification.fullscreen`) and stored once on `NotificationSettings.Default`; channel pages keep only enable, animation, notification service, display duration, and the main-window threshold. The per-channel `OverridableNotificationChannelSettings.OverrideNotificationWindowSettings` is a legacy field that `FloatingWindowSettingsUnifiedInitialized` folds back to `false` when the settings file loads, so no channel can hold a window geometry the user can no longer see or edit. - Crash recovery mode lives under `MainConfigModel.General.CrashRecovery`; prompt startup handling must run before single-instance acquisition, while normal restart must release the single-instance service before relaunch. `CrashRecoverySettingsConfig.DisableCrashedPlugin` (default enabled) gates the plugin crash auto-disable path: when a dispatcher unhandled exception stack belongs to a plugin load context, that plugin is marked `.disabled` for the next startup; the toggle lives beside the crash-recovery mode in the basic settings page. - First-run OOBE is a top-level window shown immediately after `BuildHost()` and before floating-window/main-app initialization. Its carousel begins with a non-blocking, centered welcome screen with the application icon; it is outside the eight configuration pages, whose first item places the collapsed-by-default verifiable-draw notice before the privacy-policy and GPLv3 acknowledgement controls, and whose last three are desktop integration, 集控 (control node), and privacy in that order. The control-node page sits between desktop integration and privacy on purpose: it and desktop integration are both device-local "how this machine is reached" settings that never touch `settings.json`, while privacy is "what this machine sends out" and must stay the final page that asks the user to decide something. That page binds the device-owned switch, display name, node ID, and group ID straight through `IControlNodeStateStore` (`data/config/control/node-state.json`, so an import can never turn remote control on) plus the control-platform link, and it deliberately shows **no** live connection status — the node's hosted service only starts after the OOBE closes and the Host starts, so the page states when the node connects instead of pretending to know. Each acknowledgement requires explicit confirmation. The welcome page owns the lower-left language selector; changing it persists the language, refreshes ViewModel-derived localized values, then recreates only the OOBE visual tree into localized resources without restarting or leaving the first-run flow. An active import drawer defers the visual replacement until its preview/mapping flow closes. `GuideCompleted`, `AcceptedVerificationNoticeVersion`, `AcceptedPrivacyPolicyVersion`, and `AcceptedGplVersion` determine whether an OOBE acknowledgement is required. After the full guide has completed, a verifiable-draw notice, privacy-policy, or GPL version update opens only the acknowledgement page and its privacy controls, not unrelated setup pages. OOBE class/prize spreadsheet imports reuse the list-management import controls in its own right-side drawer, so their file mapping, preview, duplicate handling, and cancel behavior stay aligned with the settings list pages. Completing OOBE continues into normal startup and explicitly opens the primary main window; it must not exit merely because the OOBE window closes. Verifiable-draw notice, privacy-policy, and GPL changes increment their app-layer OOBE versions independently. -- Floating-window startup visibility is owned by `App.ApplyFloatingWindowStartupVisibility()` and must never be left to the Avalonia lifetime. `ClassicDesktopStyleApplicationLifetime.StartCore` shows `MainWindow` **exactly once, unconditionally** (`ShowMainWindow()` is called only there and does not check visibility), so normal startup depends on that single show — while the deferred paths (first-run OOBE, settings-integrity gate) reach `App.ContinueDesktopStartup` *after* the lifetime already started and therefore get no show at all, which is how the floating window silently stayed invisible after the OOBE. Turning 启动时显示悬浮窗 off cannot be expressed by `Hide()` before `Start()` either, because `Window.Hide()` returns immediately for a window that was never shown; the hide is instead posted after the lifetime's show and gated on `UserWantsVisible`, so a tray re-open during that instant is respected and a course-linkage-hidden window is not restored. 左右两侧同时显示(默认关闭,`FloatingWindowSettings.ShowOnBothSides`)由 `App.ApplyFloatingWindowLayout()` 在运行时布置:开启后主窗钉右、副窗钉左,两扇窗都只能纵向移动,关掉开关后保留右侧那扇主窗,副窗的纵向锚点单独持久化在 `FloatingWindowSettings.SecondaryAnchorCenterY`(绝不写共享的 `FloatPosition`),且副窗跟随主窗的显示/隐藏与课程联动状态;设置改变或配置 `Reloaded` 后都会重新布置。两侧高度统一(默认开启,`FloatingWindowSettings.SyncBothSidesAnchor`,只在左右两侧同时显示开启时才出现)让两扇窗共用同一个纵向锚点:`App.AlignFloatingWindowAnchors()` 在布置与开关切换后把一侧的锚点对齐给另一侧,拖动过程中由 `App.SyncFloatingWindowAnchor()` 调 `FloatingWindow.ApplyUnifiedAnchor()` 实时跟随;关闭后两侧各记各的高度。 +- Floating-window startup visibility is owned by `App.ApplyFloatingWindowStartupVisibility()` and must never be left to the Avalonia lifetime. `ClassicDesktopStyleApplicationLifetime.StartCore` shows `MainWindow` **exactly once, unconditionally** (`ShowMainWindow()` is called only there and does not check visibility), so normal startup depends on that single show — while the deferred paths (first-run OOBE, settings-integrity gate) reach `App.ContinueDesktopStartup` *after* the lifetime already started and therefore get no show at all, which is how the floating window silently stayed invisible after the OOBE. Turning 启动时显示悬浮窗 off cannot be expressed by `Hide()` before `Start()` either, because `Window.Hide()` returns immediately for a window that was never shown; the hide is instead posted after the lifetime's show and gated on `UserWantsVisible`, so a tray re-open during that instant is respected and a course-linkage-hidden window is not restored. 左右两侧同时显示(默认关闭,`FloatingWindowSettings.ShowOnBothSides`)由 `App.ApplyFloatingWindowLayout()` 在运行时布置:开启后主窗钉在它原本那一侧、副窗补到另一侧(哪侧算"原本"由 `FloatingWindow.IsOnLeftSide` 按当前钉边/停靠状态或窗口中心与工作区中线判定),两扇窗都只能纵向移动,关掉开关后保留原本那一侧的主窗(原本在左就回左边、原本在右就留在右边),副窗的纵向锚点单独持久化在 `FloatingWindowSettings.SecondaryAnchorCenterY`(绝不写共享的 `FloatPosition`),且副窗跟随主窗的显示/隐藏与课程联动状态;设置改变或配置 `Reloaded` 后都会重新布置。两侧高度统一(默认开启,`FloatingWindowSettings.SyncBothSidesAnchor`,只在左右两侧同时显示开启时才出现)让两扇窗共用同一个纵向锚点:`App.AlignFloatingWindowAnchors()` 在布置与开关切换后把一侧的锚点对齐给另一侧,拖动过程中由 `App.SyncFloatingWindowAnchor()` 调 `FloatingWindow.ApplyUnifiedAnchor()` 实时跟随;关闭后两侧各记各的高度。 - Settings JSON, full-data ZIP, and backup restore only accept manifest/envelope exports produced by SecRandom v3. Validate `producer_version` before taking an import snapshot or changing data; unsupported sources must be explained in a modal dialog. `producer_version` is the raw `GlobalConstants.Version`, so it keeps a SemVer pre-release/build suffix (`v3.0.0-alpha.2`); the gate must strip that suffix and compare only the numeric core's major, never feed the raw value to `Version.TryParse` — otherwise a pre-release build rejects the archives it produced itself. - Security credentials must never be stored in `MainConfigModel` or `settings.json`. Keep passwords, TOTP seeds, USB binding tokens, and lockout state in `SecRandom/Services/Security`'s separate credential store; ordinary settings only select factors and protected operations. The sole credential file is `data/config/security/credentials.json`: its internal `FormatVersion` is authoritative, uses Argon2id-derived key material plus AES-256-GCM for portable storage, and must not depend on DPAPI, Keychain, `secret-tool`, or a versioned filename. Do not read or migrate older credential files. `SecurityCredentialStore` restricts the whole `data/config/security` directory to the current user once per process and on every save (Unix `0700` directory with `0600` files and temporary files; Windows breaks ACL inheritance and keeps only the current user plus SYSTEM and Administrators), because that directory also holds the readable `totp-standalone.json` copy; the hardening is best-effort and must never leave the directory unreadable to the app itself. Lockout state deliberately stays outside the AES-GCM authenticated data — a failed attempt happens without the encryption key, so `FailedAttempts`/`LockedUntilUtc` must remain writable through `SaveMetadata`, which also means anyone who can rewrite the credential file can reset the lockout: the lockout only restrains callers that cannot write that file. - The security settings themselves are no longer in `settings.json`. `SecuritySettingsConfig` (protection master switch, factor selection, protected operations, Sudo, integrity check) lives in `data/config/security/settings.json` through the app-layer `SecuritySettingsStore`: an AES-256-GCM envelope (`FormatVersion`/`Nonce`/`Tag`/`Ciphertext`, authenticated with the fixed `SecRandom/SecuritySettings/v1` associated data) plus a device-local random 256-bit key in the sibling `settings.key`. `MainConfigModel` no longer declares the property; a set-only `security_settings` bridge captures the legacy plaintext block once so the first run of this build migrates it and then rewrites `settings.json` to drop it. The read rules are load-bearing: a file that exists but cannot be decrypted, or a file that is gone while a security password is configured, must **not** fall back to "protection off" — the store returns maximal protection (`SecurityEnabled` plus every `Protect*`, with the factor flags left to the credential-derived `NormalizeSettings`) and sets `IsIntegrityCompromised`, so editing or deleting the file is never a way to turn protection off. A fresh install with no credentials still writes defaults with protection off, and the legacy bridge is consumed only while the encrypted file is absent, so neither a later `settings.json` edit nor an imported archive can re-specify these switches. The device key is what makes this work without a password prompt at startup — "should this operation verify?" must be answerable before any verification happens — so it shares the credential directory's owner-only hardening instead of the password-derived key; anyone who can read that directory can forge the settings, the same boundary as rewriting `credentials.json` to reset the lockout. - Because the protection switches left `settings.json`, `ControlSettingsCatalog` no longer describes a `security` category at all (it used to be described-but-read-only), so the control plane can neither read nor write them. The archive pre-import gate was reworked to match: `IArchivePreImportGuard.AuthorizeImport()` takes no candidate and asks the host for one fresh verification (no sudo state counts) whenever protection is active, so importing a settings file or restoring a backup stays a protected operation even though no archive can carry the switches any more. Export is deliberately not gated: automatic and cloud backups run in the background where no dialog can be raised. The whole `data/config/security` directory — now also holding the protection switches — stays excluded from every export, cloud backup, and the Android provider. - While `SecuritySettingsConfig.RequireAllSelectedFactors` is off ("any selected method" mode) every selected factor verifies on its own, and TOTP cannot be checked without its seed, so that mode keeps a password-free seed copy in the sibling `data/config/security/totp-standalone.json` (written only while the mode is off and TOTP is configured; deleted when the mode turns on or the password is removed). The directory stays excluded from every export, cloud backup, and the Android provider, and the settings description discloses the trade-off. Never move that copy into `credentials.json`: its AES-GCM authentication data covers only `FormatVersion`, the password credential, `HasTotp`, and USB bindings, so a readable seed field there would be read before any authentication and would silently bypass the existing tamper detection. -- `SecuritySettingsConfig.SettingsIntegrityCheckEnabled` (desktop-only, password-gated) records a SHA-256 fingerprint of the whole `data/config/settings.json` in the credential envelope's plaintext `SettingsIntegrity` record on every `MainConfigHandler.Save()`/`Reload()`, and `App` verifies it before desktop startup. A mismatch routes through `SettingsIntegrityAction`: `Confirm` (the default) keeps the confirmation gate that requires the security password before the app continues, otherwise it exits; `AutoRestore` hands startup to `SettingsIntegrityRecoveryService`, which walks the newest `data/backup/*.zip` and/or account cloud backups per the separately configured `SettingsIntegrityRestoreSource` (`Local` / `LocalThenCloud` / `CloudThenLocal`), takes `config/settings.json` from the first supported v3 archive that actually carries a loadable settings payload, copies the current file to `data/backup/integrity/settings_before_restore_*.json`, atomically replaces it, reloads the handler (which refreshes the fingerprint), and restarts the app; only the settings file is touched, and a failed recovery keeps the original file and falls back to the password gate with the failure reason. Cloud candidates go through `SettingsIntegrityRecoveryService.OrderCloudCandidates`, which keeps *only* backups uploaded by this device (`CloudBackupService.IsOwnBackup`, newest first) and drops every other machine's: a settings file describes the machine it came from, so another device's backup is never a restore source, not even as a last resort. When this device has no own cloud backup the cloud source yields nothing (the skip is logged), recovery stays with `data/backup`, and otherwise the original file is kept and startup falls back to the password gate. The fingerprint needs existing security credentials as its anchor, is cleared when protection is turned off, and — because it lives outside the AES-GCM authenticated data — detects accidental or casual edits rather than a determined local attacker who can rewrite both files. Because the switch itself now lives in the encrypted security-settings file, `SettingsIntegrityService` also subscribes to `SecuritySettingsStore.Saved`: toggling the check no longer writes `settings.json`, so that event is what records or clears the fingerprint — without it the check could be turned on and still never have a recorded digest. - OmniTTS cloud speech API keys are credentials too: they live in `data/config/voice/omnitts-keys.json` via `OmniTtsCredentialStore` (app-layer, atomic replace), never in `VoiceSettingsConfig`/`settings.json`, IPC payloads, logs, telemetry, backups, or the Android DocumentsProvider. OmniTTS is voice engine 2 (`OmniTtsSpeechProvider.OmniEngine`), sits beside System SAPI (0) and Edge TTS (1), and is a unified cloud TTS engine whose providers are OpenAI, Gemini, FishAudio, MiMo, and Custom OpenAI-compatible. OpenAI, Gemini, and MiMo voice choices use documented preset sets; Gemini uses native `/v1beta/interactions` synthesis and wraps its 24 kHz PCM response as WAV. MiMo voice-design and voice-clone models use model-specific chat-completions payloads; clone references are WAV files kept privately under `data/config/voice/mimo-voice-reference.wav`, identified by a hash, and excluded from settings, archives, IPC, and logs. Models are fetched from provider APIs or typed manually. The voice settings page shows OmniTTS-specific rows (provider, base URL, key, model, voice, batch cache) only while `VoiceEngine == 2`. `data/config/voice/` is excluded from archives and protected from the Android provider/directory launcher. iOS keeps the voice settings page unregistered (`!OperatingSystem.IsIOS()`); OmniTTS targets Windows, Linux, macOS, and Android. - Security authorization always flows through `ISecurityService`; do not add direct validation checks to tray handlers, windows, ViewModels, or linkage code. Passwords require at least 6 characters, with no artificial character-class rule. Strength feedback is advisory only: the password editor renders `PasswordStrengthEvaluator` (`SecRandom.Core/Services/Security/PasswordStrength/`, zxcvbn-style dictionary/pattern guess-count bands), and that score must never become a save gate — a rule-shaped "must contain X" meter is the same artificial constraint this section forbids. - Sudo mode is opt-in but on by default (`SecuritySettingsConfig.SudoModeEnabled`); turning it off makes every protected operation verify again. While it is on, a successful verification skips re-verification for `SudoModeDurationSeconds` (default 20s, 10–600s in the security page). The global timer covers draw/window/restart/exit/shortcut/IPC operations, while the settings window keeps a separate timer that is renewed by every verified settings update and ends when the duration elapses **or** the settings window closes, whichever comes first. Sudo never covers protection-loosening changes: `UpdateSecuritySettingsAsync` diffs the security settings with `SecuritySettingsSnapshot.IsProtectionDowngrade`, and a downgrade (turning security off, clearing a factor, disabling the settings-integrity check, switching the integrity action to automatic restore, turning a protection off, or lengthening the sudo duration) requires a fresh password verification that neither the settings-window sudo nor the global timer can satisfy; that fresh verification then authorizes further downgrades for one sudo duration so a single editing session does not re-prompt for every switch. `BypassClassTimeRestriction` and `ChangeSecuritySettings` are deliberately immune to every sudo state, so a confirmed non-class-time restriction can never be bypassed by an open sudo window. TOTP setup (`BeginTotpSetupAsync`), TOTP removal (`RemoveTotpAsync`, which clears the seed from the credential envelope, deletes the `totp-standalone.json` copy, discards any unconfirmed pending setup, and turns the factor off), password changes, and USB binding always require fresh verification too. The tray menu exposes an "Exit Sudo Mode" option (visible while any sudo state is active) that calls `DeactivateSudoMode()` and therefore clears both the global timer and the settings-window authorization. Every security-setting control on the security page — including the Sudo switch and duration — must write through `UpdateSecuritySettingsAsync`; never mutate the security-settings model directly and save it, because `UpdateSecuritySettingsAsync` is what performs the fresh verification and `SecuritySettingsStore` is what writes the encrypted file. @@ -179,7 +174,7 @@ Keep this map short and stable. When code moves, AI agents should re-read the mo - File persistence saves are atomic replacements: `FileConfigService.SaveConfig` and `DrawTemporaryRecordService.SaveState` write a temporary file and atomically replace the target; new file-persistence code must follow the same pattern instead of overwriting files in place. Profile history is stored in SQLite (`ProfileHistoryDatabase`) instead: it saves inside one transaction, so a crash rolls back to the previous complete history, and it never needs the temp-file dance. Do not hand-build history paths — `ProfileHistoryPaths` owns the database, the not-yet-migrated JSON and the `.json.migrated` backup for a profile. - Draw proofs use the SecRandom v3 algorithm ID and an `algorithmEngineVersion`. Engine v3.1 commits the sampling mode into the request: student draws use history-balanced weighted sampling, count-based lottery inventory uses equal-probability partial permutation when no internal rule applies, and pan or internal-rule lottery draws use weighted sampling without replacement. Keep the verifier's replay logic byte-compatible with each supported proof engine version. Engine v3.4.0 does not change the replay mathematics at all — it only marks that the `fairness` block may carry `historyScope` — but the service side must be deployed **before** a client build sends that generation, exactly like a new audit field: a 3.3-generation verifier replays the same proof and reads the narrowed per-candidate `historyCount` values as global history. `fair.sectl.cn` accepts 3.4/3.3/3.2 as the current algorithm family, 3.1 as the previous family, and 3.0 as the oldest, and keeps replaying every previously issued generation. - Ordinary draws immediately save an `OfflineReproducible` proof, then submit that newly generated proof to `fair.sectl.cn` for background replay/signing. A submission must use the proof object captured at draw time and never a re-read of the proof file: `DrawProofAttestationService` keeps the pending item in memory, persists only its path, proof ID, and canonical proof hash to `data/proofs/attestation-queue.json`, retries failures with bounded exponential backoff, resumes queued items after a restart, and refuses plus reports an item whose file no longer matches the recorded hash (it then keeps the receipt in the queue instead of overwriting the changed file). Startup must never scan or re-attest historical proof files that were never queued. A current server receipt signs a canonical hash of all proof fields except the receipt itself, plus the proof ID, input hash, payload hash, anonymous audit-payload hash, and mode; public sharing requires that receipt. This detects changes after the signed submission, but it does not attest to an unmodified local executable, an authentic real-world candidate pool, or absence of pre-draw result selection. Do not call it a pre-draw server witness. Local proof retention applies both the configured age and total storage limits; after every new save, delete oldest `.srproof.json` files until the configured storage cap is met. -- `data/proofs` carries a local append-only evidence chain: `DrawProof.Chain` stores `index`/`prevHash`/`selfHash` (`selfHash = SHA256("SecRandomProof/v3/chain" ‖ index ‖ prevHash ‖ canonicalProofHash)`), and `ProofChainStore` keeps the head plus a `retainedFromIndex` floor in `data/proofs/chain-head.json`. Retention and storage-limit cleanup must record every proof they delete through `RecordRemovedIndices`, so an absence below the floor is explained and only an unrecorded prefix/interior gap is reported; the floor may only advance across a contiguous prefix of recorded removals, because a sparse deletion (removing index 10 while 1-9 survive) would otherwise explain away every hole below it; storage-limit cleanup must also never delete the proof the same save just wrote, since that leaves the chain head pointing at a file that never landed and hands the attestation queue a path that no longer exists; `ProofIntegrityVerifier` is the only reader that judges the chain. Chain fields and `witness.timestampToken` must never enter `WitnessClient.ComputeAttestedProofHash` — the server recomputes that hash, so adding fields there invalidates every receipt. A local chain buys visibility, not protection: an attacker who controls the machine can rebuild chain and head consistently. +- Proof files under `data/proofs` are plain `OfflineReproducible` `.srproof.json` documents. The local append-only evidence chain was removed: `DrawProof.Chain`, `ProofChainStore` (`data/proofs/chain-head.json`), `RecordRemovedIndices` cleanup notes, and `ProofIntegrityVerifier`. Receipts issued before the removal stay valid because `WitnessClient.ComputeAttestedProofHash` never covered chain fields — so never add them back to that hash, and do not re-introduce a chain reader or a verification-page chain button. - The anonymous audit payload is validated by `fair.sectl.cn` against a fixed property allow-list (`ValidateAnonymousAuditPayload` / `ValidateFairness`), so adding a field there requires the server change to land first — the client must never ship a new audit field before the service accepts it, or every ordinary attestation fails with `audit_payload_invalid`. `rosterDigest` was added that way: `RosterDigest.Compute` hashes the canonical RecordId-to-display mapping (entries sorted by record id, so reordering is not a change while renaming, renumbering, regrouping, or disabling is) of the roster the draw was taken from, and `VerificationDrawCoordinator` omits it when the active profile is not the drawn list. It is the only commitment that ties a winning record id back to a person, because the candidate pool itself is anonymous — without it, editing the list after the draw silently re-points a winning record id at someone else while every receipt, replay check, and time stamp still validates. Only the digest leaves the device, never names or numbers; the digest of a low-entropy roster does allow someone who already knows nearly the whole list to confirm a membership guess. RFC 3161 time stamping is always on and has no user-facing setting: `TimestampAuthorityClient` sends only the canonical proof hash to the fixed authority `https://tsa.wotrus.com/`, stores the returned token in `witness.timestampToken`, and validates its signature plus the certificate chain, accepting either the operating-system trust store or the pinned WoTrus (沃通) root it embeds (revocation is not checked so validation stays offline-capable). The authority is deliberately not configurable — a user-facing URL would let a broken or hostile endpoint silently disable the anchor — and it is reachable from mainland networks, unlike the free public authorities. A time stamp proves the digest existed no later than the stamped time and never that the draw happened then. `historyScope` follows the same allow-list rule: `ValidateFairness` accepts `global`/`course`/`history-group`/`course-and-history-group`, and the client declares only the scope — **never** the group name, which is user-authored free text that can name a class or a person. The service cannot verify the claim either, because it only replays the recorded per-candidate `historyCount` values, so `historyScope` is a declaration attached to the proof, not an attestation of how the history was filtered. - `fair.sectl.cn` anchors the local proof chain: `DrawProofAttestationService` submits the proof including `chain`, and the attest response's `chain.status` (`genesis`/`continuous`/`duplicate`/`broken`/`gap`/`behind`/`conflict`) is surfaced as `ProofAttestationStatus.ChainAlertCount` and logged. A `behind` status means the service already holds a higher chain position for this device, which is how a deleted-and-rebuilt local chain becomes visible; the server-side anchor never moves backwards. Receipt and time-stamp failures are counted separately (`ReceiptFailedCount`/`TimestampFailedCount`) so an unavailable third-party authority never reads as a failed attestation. - Formal notarization is the explicit alternative to ordinary replay attestation: the client sends a zero-seed anonymous request, `fair.sectl.cn` durably locks it, persists server random material after the lock, calculates the result, and returns an immutable `OnlineWitnessed` proof. Formal mode waits for that response and must never substitute a local draw after an error; its ledger is independent of retention-limited public proof sharing. It protects the locked flow against local code/seed/proof replacement, but cannot establish real-world roster authenticity, completeness, or pre-submission pool integrity. @@ -193,7 +188,6 @@ Keep this map short and stable. When code moves, AI agents should re-read the mo - The desktop loopback redirect is answered with `LoopbackAuthCallbackPage` rather than a bare `

`. Its wording must never claim a finished sign-in — `SectlAuthService` writes and closes that response *before* it validates `state` and exchanges the code — and its light/dark follows the browser's `prefers-color-scheme`, because a page in the browser cannot read the app theme. `LoopbackAuthRedirectBroker` keeps answering requests that carry neither `code` nor `error` (a browser asking for `/favicon.ico`, a reload) instead of spending its one read on them, and a browser that closes the tab mid-write must not turn an already-received callback into a failure. Responses carry `default-src 'none'` CSP, `no-store`, and `nosniff`, and the page stays static — no entrance animation, because a background tab or a screenshot must never catch it invisible. - The settings title bar account flyout and the mobile cloud tab use `SectlAuthService` and SECTL OAuth Authorization Code + PKCE. Desktop receives the redirect on a loopback callback; a mobile head receives it through the app's custom scheme (`cn.sectl.secrandom.mobile://oauth/callback`, registered on the SECTL authorization service for the shared client id), delivered by `MobileAuthCallbackRouter` — Android through the system browser and an intent filter, iOS through `ASWebAuthenticationSession`, which captures the redirect itself because a suspended iOS app cannot be handed a deep link. Tokens are stored only in `data/config/sectl-auth.json` through `SectlTokenStore`; the client ID is centralized in `SectlAuthService.ClientId`, and a mobile attempt records its PKCE verifier in `data/config/sectl-auth-pending.json` so a redirect that arrives after the process was reclaimed is still exchanged (`SectlAuthService.ResumePendingAuthorizationAsync`, never a second authorization prompt). The refresh endpoint rotates a **single-use** refresh token on every success and invalidates the previous one immediately, so the client contract is: `SectlTokenStore.SaveAsync` replaces the file atomically (temporary file + flush to disk + rename) and a rotation is persisted *before* the new access token is used — never memory-first, never in place; all concurrent refreshes collapse into one single-flight task (callers await it with their own cancellation token, so one caller giving up cannot abort a rotation the others need) under a cross-process lock file (`sectl-auth.lock`) that also makes a second process re-read and adopt a pair another process already rotated. Outcomes are classified instead of retried blindly: `400` (`invalid_grant`/`invalid_request`/`unsupported_grant_type`) and `401 invalid_client` are terminal — the local pair is cleared, `RequiresReauthorization` is set, `StateChanged` fires, and the dead refresh token is never submitted again; `429 rate_limited` retries the *same* refresh after its `retry_after_ms`; `503 temporarily_unavailable` retries with exponential backoff plus jitter; an unknown network outcome first re-reads the token file (adopting another process's rotation) and then retries once, and keeps the session when it still cannot tell whether the server rotated. Access tokens carry a locally stamped `access_token_expires_at` and are refreshed five minutes early (`expires_in` from the response, 3600s fallback), while `refresh_token_issued_at` records the first authorization because the fixed 180-day window is never extended by rotation. `SectlHeartbeatService` calls `/api/oauth/heartbeat` with the active Bearer token immediately after startup/sign-in and then every five minutes, independent of the anonymized online-status policy. `SectlAuthService.SendAuthorizedAsync` is the one authorized-request boundary for other SECTL APIs: it attaches the bearer token, refreshes it once on `401`, and treats `error_description: Access token has been revoked` as a reason to re-authorize rather than to rotate the refresh token. `SectlAuthService.InitializeAsync` must stay local-only: it loads the token file and raises `StateChanged`, while the `/api/oauth/userinfo` profile and avatar download run on an unobserved background task that reports through the same event. `App.StartRuntimeServicesAsync` awaits account initialization before `Host.StartAsync()`, and `ShowSettingsWindowCoreAsync` awaits that startup task, so awaiting the account network calls there makes a slow SECTL API stall every window that follows — the settings window must never depend on account network latency. The `/api/oauth/token` and `/api/oauth/refresh` payloads carry only the grant fields plus the device UUID: the client must not resolve its own public IP (the former third-party lookup call is gone for good) nor upload an `ip_address`, because the service derives the address from the connection itself. - SECTL OAuth tokens never expire by time: the service keeps `ACCESS_TOKEN_TTL_SECONDS` and `REFRESH_TOKEN_TTL_SECONDS` at `-1`, reports `expires_in = 315360000` (ten years) only so a generic OAuth client can still compute a far-away absolute expiry, and `/api/oauth/introspect` answers `expires_at: "-1"` with `exp: null`. No local age check may therefore end a session: `SectlAuthService.ResolveAccessTokenLifetime` maps a negative or absent lifetime to `UnlimitedExpiresInSeconds`, and revocation is the only end — an explicit logout/revocation, a reused refresh token (family revocation), or a deleted account. `SectlAuthService.InitializeAsync` confirms the stored session in the background with `POST /api/oauth/introspect` (`token` + `client_id`, mapped by `SectlTokenIntrospection` in `SecRandom/Services/Auth/SectlTokenIntrospection.cs`) and never on the awaited startup path: `active: false` clears the pair, sets `RequiresReauthorization`, and raises `StateChanged`, while an unreachable endpoint, a non-success status, or a malformed body keeps the session — a flaky network must never read as a revoked session. `SectlTokenIntrospection.NeverExpires` documents the `"-1"` marker so nobody parses it as a date, which would read as 2000-12-31 and discard a fresh session. The `85.137.245.159` host in the developer `~/.ssh/config` is the separate sync server, not the auth or cloud service, so no API origin may be derived from it. -- Account cloud backup is an app-layer feature on desktop and mobile, built on the SECTL personal cloud API (`/api/cloud/*`), and is separate from the anonymous SecRandom Sync channel, which stays encrypted, short-lived, and 1 MiB-capped. `DataArchiveService.ExportCloudBackupAsync` produces a `CloudBackup` archive whose root set is picked from the dedicated `CloudInclude*` selection but never leaves `CloudBackupRoots`, so `config/device-uuid.json`, `audio/voice`, `theme`/`themes`, and `logs` can never be uploaded (plugins, credentials, backups, and staging were already excluded for every archive kind), while `proofs` is uploadable only when `BackupConfig.CloudIncludeProofs` is on — default off, because a cloud copy is the last resort once local proofs were deleted; `ImportCloudBackupAsync` accepts only that kind and filters the device identity out of its commit roots. One backup is uploaded as 512 KiB verified parts plus a trailing manifest, cloud state is always rediscovered by listing (`SecRandom-cloud-` prefix, parts grouped per backup) instead of being cached in configuration, and a download must pass per-part and whole-archive SHA-256 verification before the normal v3 inspection, recovery snapshot, staging commit, and restart request. Client-side encryption and its passphrase were removed on purpose: the archive is uploaded as produced, so account access is the only key and any signed-in device can list and restore any backup — the platform can read a cloud backup, which is the accepted trade-off for recoverability. A package the removed feature uploaded is still recognised by its `-enc` file-name marker and stays listed with a 旧版加密,无法恢复 label, but `CloudBackupService.CanRestore` is false for it and its schema-2 manifest is rejected by `ValidateManifest`, because this build holds no way to derive its key. The cleartext manifest still reveals which content categories a backup carries and its size. Automatic cloud backup is opt-in and separate from the local backup cadence (`BackupConfig.CloudAutoBackupEnabled`/`IntervalDays`/`MaxCount`); the `CloudAutomaticBackupService` runs it while an account is signed in and follows this device's own newest upload, and only `CloudBackupService.UploadAutomaticAsync` may delete cloud backups. Every upload stamps a device alias into its backup id (`CloudBackupPackage.CreateBackupId`, `_`, ASCII-safe and at most `MaxDeviceTagLength` characters, taken from `BackupConfig.CloudDeviceAlias` or the host name, with a short digest when neither is ASCII-safe), so the cloud listing shows which machine a backup came from without downloading its manifest; the alias is a display label rather than an identity, so `config/device-uuid.json` still never leaves the device. Retention is per device: `UploadAutomaticAsync` trims only this device's surplus beyond `MaxCount` and never deletes a backup it cannot attribute (ids uploaded before aliases existed stay untrimmed), while an exhausted quota is the one account-wide deletion and removes the oldest backup of the whole account. The manual upload path never deletes implicit backups. - Desktop plugins use `.srpx` ZIP packages with a root `manifest.yml`; the entry assembly contains one non-abstract `PluginBase` implementation. Plugins are discovered from `data/plugins`, pending packages are staged in `data/cache/plugin-packages`, and plugin initialization runs before Host construction. Plugin page IDs follow the `plugin..*` namespace, are owned by the plugin, and must be unique at the application registry level. External dynamic plugins are desktop-only for now; mobile hosts do not load them. - Plugin API surface: `PluginBase` implements `IAsyncDisposable`; the host disposes each entrance (`DisposePluginsAsync`) before Host shutdown, and forwards application start/stop to the `PluginBase.OnAppStarted` / `OnAppStopping` overrides through the `PluginLifecycleBridge` hosted service (no plugin-registered hosted service needed just for lifecycle). Stable plugin-facing contracts resolve through DI from `SecRandom.Core/Abstraction/Services/`: `IMainView`/`ISettingsView`/`IDrawerView` (under `Views/`, wrapping `MainView.Current`/`SettingsView.Current` with UI-thread marshaling and empty-shell no-ops), `IAppNavigationService` (wraps `App.ShowMainWindow`/`ShowSettingsWindow`/`ShowQuickDrawWindow` and preserves the settings authorization gate), `IAppLifecycleService` (forwards `App.AppStarted`/`AppStopping`; primary use is plugin lifecycle hooks), `IFloatingWindowButtonRegistry` + `FloatingWindowButtonDescriptor` (runtime-only floating-window button registration; visibility is picked in the floating-window settings MultiComboBox and persisted as `FloatingWindowSettingsConfig.VisiblePluginButtonIds`, pruned at refresh when a registration disappears), and `IPluginDrawService` (controlled draw facade). Plugin draws must go through `IPluginDrawService`, which authorizes via `LinkageDrawCoordinator` and reuses `RollCallDrawService`/`LotteryDrawService`; plugins must never call `IDrawCommitService`, `IRollCallSession`/`ILotterySession`, or `IProfileService.Record*History` directly. Plugin management supports uninstall markers (`.uninstall`, config dir preserved), crash auto-disable (`.disabled` written when an unhandled exception stack belongs to a plugin load context), and external dev plugin directories via repeatable `--epp`/`--externalPluginPath` startup args. `PluginManager` is registered as both `IPluginManager` and its concrete type. The srpx packaging target excludes host-provided assemblies (SecRandom/Avalonia/FluentAvalonia/Microsoft.Extensions/runtimes/resources) so plugin packages stay host-free even with the local SDK reference. The full guide is `docs/plugins.md`. - Plugin SDK packaging and release: `SecRandom.PluginSdk` tracks the application version. `PluginApiVersions.Current` in the SDK defines the minimum host API version and its major must equal the application major version (enforced by the `build_pluginsdk` CI job). `SecRandom.Shared`, `SecRandom.Core`, and `SecRandom.PluginSdk` are packed together on every CI run (`-p:PackageVersion=`) and uploaded as the `pluginsdk` artifact; only the release `publish` job pushes them to NuGet.org using `NuGet/login@v1` (OIDC Trusted Publishing, `user=${{ secrets.NUGET_USER }}`). The host rejects plugins whose `manifest.yml` `apiVersion` major is below `PluginApiVersions.Current.Major`. Local pack workflow: `scripts/publish-pluginsdk.ps1`. @@ -219,8 +213,9 @@ Keep this map short and stable. When code moves, AI agents should re-read the mo - Course linkage uses fixed v2 data-source values: `0=Off`, `1=CSES`, `2=ClassIsland`. CSES schedules live at `data/CSES/cses_schedule.yml`; ClassIsland is accessed only through the app-layer official IPC adapter. Only a confirmed course break restricts local draw/reset or hides the floating window. Missing/invalid CSES data, ClassIsland connection loss, or an unknown state must permit normal operation. ClassIsland reports a confirmed non-class period as `Breaking`, `AfterSchool`, `PrepareOnClass`, or `None` (today's plan loaded but no current time point, i.e. before the first class or a gap); `IsLessonConfirmed` is only true inside a class/break time point and must never be used as an availability gate, because before-school and after-school hours are exactly the periods the linkage restriction must cover. A day without a loaded plan (`IsClassPlanLoaded == false`) stays permissive. - CSES schedule errors follow the “`InvalidDataException` + `Data` error code” convention: `CsesScheduleException` is a static factory that throws `InvalidDataException` (sealed, so it cannot be subclassed) with a `CsesScheduleError` code and optional argument stored in `Exception.Data`; UI retrieves them through `CsesScheduleException.TryGetError` and localizes from resources. - `LinkageSettings.VerificationRequired` governs the course-time bypass prompt and is distinct from `SecuritySettings.ProtectLinkage`, which continues to protect only external SecRandom URL/IPC mutations. Student course history uses `HistoryItem.CourseName` with `RecordId` identity; empty legacy course values remain global history. -- File/data paths should go through `Utils.GetFilePath(...)`. Desktop and portable deployments keep mutable data under the package root's `data/` directory. The shared `App` mobile branch is the controlled exception: before any path is read, it sets `Utils` once to its app-private local-data root; no Core service, view, or desktop code may redirect it later. `data/config` keeps its stable name for compatibility but is hidden at the filesystem level where supported (Windows `Hidden|System`; Unix-like hosts use the parent `.hidden` convention as a fallback), and hiding failures must not block config I/O. -- Desktop startup calls `Utils.PrepareDesktopDataRoot()` before reading settings. Installed packages use `/data` when it passes a real write probe and otherwise use `LocalApplicationData/SecRandom/data`; portable ZIP packages never fall back to a per-user directory, and a failed write probe blocks startup with the transient `SecRandomTmpRootWindow`/`FATaskDialog` warning host. +- File/data paths should go through `Utils.GetFilePath(...)`. The desktop data root is resolved in `SecRandom.Shared/DataRoot/` (`DesktopDataRootResolver`) with one fixed precedence: `--data-root` > `SECRANDOM_DATA_ROOT` > the anchor file `data-root.json` > legacy-location adoption > mode default. Portable packages default to `/data`; installed packages default to a per-user standard root (`%LOCALAPPDATA%\SecRandom\data`, macOS `~/Library/Application Support/SecRandom/data`, Linux `${XDG_CONFIG_HOME:-~/.config}/secrandom/data`) and never to the install directory. The anchor lives outside the data root (`/data-root.json` for portable, the standard anchor directory for installed). A user-chosen root is a `Custom` mode stored in that anchor; a root inside an activated `app-*` payload is never a valid destination. The shared `App` mobile branch is the controlled exception: before any path is read, it sets `Utils` once to its app-private local-data root; no Core service, view, or desktop code may redirect it later. `data/config` keeps its stable name for compatibility but is hidden at the filesystem level where supported (Windows `Hidden|System`; Unix-like hosts use the parent `.hidden` convention as a fallback), and hiding failures must not block config I/O. +- Desktop startup calls `Utils.PrepareDesktopDataRoot(GlobalConstants.IsDevelopment, commandLineDataRoot)` before reading settings. The resolver adopts legacy layouts (`/data`, a writable install directory's `data`, a stray `app-*/data`) and repairs payload-resident data by moving it to the package root; a failed write probe blocks startup with the transient `SecRandomTmpRootWindow`/`FATaskDialog` host (`M_DataRootUnavailable*`, or the portable-specific message). The anchor is persisted whenever the mode came from a default/legacy/adopted location, and is not written for a command-line/environment override or for development builds already resolving the package directory. +- Changing the data root is a two-process transaction: the storage settings page validates the target, writes `data-root-journal.json` (next to the anchor), and restarts with `--data-root-migration `; that launch skips normal data-root preparation and shows `DataRootMigrationWindow`, which runs `DataRootMigrationEngine` (copy to `.migrating-` on the target volume, rewrite root-relative paths, verify, rename to the target, write the anchor, then keep the old root as `.migrated-`). Writing the anchor is the single commit point: if it fails the target is rolled back and the source stays intact. - Desktop builds copy `SecRandom/Assets` beside the executable and bind `OverlayAssetLoader` so existing `avares://SecRandom/Assets/...` URIs load physical files first, including Debug builds. Android and iOS keep the same assets embedded. `Assets/Updates/release-public-key.txt` and `Assets/Plugins/plugin-market-public-key.txt` are embedded on every target and must never be resolved from the physical overlay. `System.Uri` lower-cases the authority of an absolute `avares` URI while the scheme is unregistered (as it is for the `GlobalConstants` static font families created before Avalonia starts), so the overlay must compare that authority case-insensitively, or the first layout asking for the `Assets/Fonts/` font collection throws `Could not create glyphTypeface`. - Portable ZIP updates use `SecRandom.Launcher` at the stable package root and activated `app-*` payload directories. The application, not Launcher, validates/downloads/extracts/activates a complete ZIP; `Utils.PackageRoot` / `DataRoot` keep user data stable across payload versions. Every entry that outlives the process — autostart and `secrandom://`/URL-protocol registration — must launch that root Launcher (`Utils.TryGetPortableLauncherPath`) instead of an executable inside the activated payload, because an update replaces that directory; in-app restart and crash recovery keep using the running payload's executable. - Update discovery uses a fixed GitHub mirror first, with GitHub direct access as fallback. A detached Ed25519-signed release manifest and each artifact's length/SHA-512 must verify before deployment or a system installer is started; signing keys remain outside the repository. Desktop artifacts, the signed Android arm64 APK, and the unsigned iOS arm64 IPA share this manifest. Android downloads its verified APK then delegates installation to the system package installer; iOS device distribution and in-app update delivery remain deferred. diff --git a/SecRandom.Core.Tests/BackupConfigTests.cs b/SecRandom.Core.Tests/BackupConfigTests.cs index f1486500e..1afba8574 100644 --- a/SecRandom.Core.Tests/BackupConfigTests.cs +++ b/SecRandom.Core.Tests/BackupConfigTests.cs @@ -30,19 +30,26 @@ public void BackupDefaultsAndLegacyConfigIncludeDrawProofFiles() } [Fact] - public void CloudBackupDefaults_StayOffAndKeepImagesOutOfTheUpload() + public void LegacyCloudBackupFields_AreIgnoredAndLocalFieldsStillLoad() { - MainConfigModel defaults = new(); - BackupConfig backup = defaults.General.Backup; - - Assert.False(backup.CloudAutoBackupEnabled); - Assert.Equal(5, backup.CloudAutoBackupMaxCount); - Assert.Equal(string.Empty, backup.CloudDeviceAlias); - Assert.False(backup.CloudIncludeImages); - Assert.False(backup.CloudIncludeAudio); - Assert.False(backup.CloudIncludeProofs); - Assert.True(backup.CloudIncludeConfig); - Assert.True(backup.CloudIncludeList); - Assert.True(backup.CloudIncludeHistory); + const string legacyJson = """ + { + "general": { + "backup": { + "cloud_auto_backup_enabled": true, + "cloud_auto_backup_max_count": 9, + "cloud_device_alias": "old-device", + "cloud_include_images": true, + "auto_backup_interval_days": 3 + } + } + } + """; + + MainConfigModel? restored = JsonSerializer.Deserialize(legacyJson, ConfigServiceBase.JsonOptions); + + Assert.NotNull(restored); + Assert.Equal(3, restored.General.Backup.AutoBackupIntervalDays); + Assert.True(restored.General.Backup.IncludeProofs); } } diff --git a/SecRandom.Core.Tests/CloudBackupPackageTests.cs b/SecRandom.Core.Tests/CloudBackupPackageTests.cs deleted file mode 100644 index e2706e4f5..000000000 --- a/SecRandom.Core.Tests/CloudBackupPackageTests.cs +++ /dev/null @@ -1,306 +0,0 @@ -using System.Security.Cryptography; -using SecRandom.Core.Services.Archive; - -namespace SecRandom.Core.Tests; - -public sealed class CloudBackupPackageTests -{ - private const string BackupId = "20260830-120000-abcd1234"; - - [Fact] - public void Slice_SplitsArchiveIntoOrderedPartsOfTheConfiguredSize() - { - var archive = CreateBytes(CloudBackupPackage.DefaultPartBytes * 2 + 17); - - var parts = CloudBackupPackage.Slice(archive, CloudBackupPackage.DefaultPartBytes); - - Assert.Equal(3, parts.Count); - Assert.Equal(CloudBackupPackage.DefaultPartBytes, parts[0].Length); - Assert.Equal(CloudBackupPackage.DefaultPartBytes, parts[1].Length); - Assert.Equal(17, parts[2].Length); - Assert.Equal(archive, parts.SelectMany(part => part).ToArray()); - } - - [Fact] - public void BuildManifest_RejectsArchiveAboveTransferLimit() - { - var oversizedArchive = new byte[16 * 1024 * 1024 + 1]; - - Assert.Throws(() => CloudBackupPackage.BuildManifest( - BackupId, [oversizedArchive], oversizedArchive.Length, ["list"], DateTime.UtcNow, "v3.0.0", oversizedArchive)); - } - - [Fact] - public void BuildManifest_RecordsPartNamesLengthsAndHashes() - { - var archive = CreateBytes(CloudBackupPackage.DefaultPartBytes + 5); - var parts = CloudBackupPackage.Slice(archive, CloudBackupPackage.DefaultPartBytes); - - var manifest = CloudBackupPackage.BuildManifest(BackupId, parts, CloudBackupPackage.DefaultPartBytes, - ["config/settings.json", "list"], new DateTime(2026, 8, 30, 12, 0, 0, DateTimeKind.Utc), "v3.0.0-beta.1", archive); - - Assert.Equal(CloudBackupPackage.Format, manifest.Format); - Assert.Equal(CloudBackupPackage.SchemaVersion, manifest.SchemaVersion); - Assert.Equal(BackupId, manifest.BackupId); - Assert.Equal("v3.0.0-beta.1", manifest.ProducerVersion); - Assert.Equal(CloudBackupPackage.BuildArchiveName(BackupId), manifest.ArchiveName); - Assert.Equal(archive.LongLength, manifest.ArchiveBytes); - Assert.Equal(CloudBackupPackage.Hash(archive), manifest.ArchiveSha256); - Assert.Equal(["config/settings.json", "list"], manifest.Roots); - Assert.Equal(2, manifest.Parts.Count); - Assert.Equal(CloudBackupPackage.BuildPartName(BackupId, 1, 2), manifest.Parts[0].Name); - Assert.Equal(CloudBackupPackage.BuildPartName(BackupId, 2, 2), manifest.Parts[1].Name); - Assert.Equal(parts[0].LongLength, manifest.Parts[0].Length); - Assert.Equal(CloudBackupPackage.Hash(parts[0]), manifest.Parts[0].Sha256); - CloudBackupPackage.ValidateManifest(manifest); - } - - [Fact] - public void Manifest_RoundTripsThroughJson_AndMergesBackToTheOriginalArchive() - { - var archive = CreateBytes(CloudBackupPackage.DefaultPartBytes * 2 + 9); - var parts = CloudBackupPackage.Slice(archive, CloudBackupPackage.DefaultPartBytes); - var manifest = CloudBackupPackage.BuildManifest(BackupId, parts, CloudBackupPackage.DefaultPartBytes, - ["list"], DateTime.UtcNow, "v3.0.0", archive); - - var restored = CloudBackupPackage.DeserializeManifest(CloudBackupPackage.SerializeManifest(manifest)); - - Assert.Equal(manifest.BackupId, restored.BackupId); - Assert.Equal(manifest.ArchiveBytes, restored.ArchiveBytes); - Assert.Equal(manifest.ArchiveSha256, restored.ArchiveSha256); - Assert.Equal(manifest.Parts.Select(part => part.Name), restored.Parts.Select(part => part.Name)); - Assert.Equal(manifest.Parts.Select(part => part.Sha256), restored.Parts.Select(part => part.Sha256)); - Assert.Equal(archive, CloudBackupPackage.MergeAndVerify(restored, parts)); - } - - [Fact] - public void TryParseFileName_RecognizesPartsAndManifests_AndRejectsForeignNames() - { - Assert.True(CloudBackupPackage.TryParseFileName( - CloudBackupPackage.BuildPartName(BackupId, 3, 7), out var partId, out var index, out var count, out var isManifest)); - Assert.Equal(BackupId, partId); - Assert.Equal(3, index); - Assert.Equal(7, count); - Assert.False(isManifest); - - Assert.True(CloudBackupPackage.TryParseFileName( - CloudBackupPackage.BuildManifestName(BackupId), out var manifestId, out _, out _, out var manifestFlag)); - Assert.Equal(BackupId, manifestId); - Assert.True(manifestFlag); - - Assert.False(CloudBackupPackage.TryParseFileName("holiday-photo.png", out _, out _, out _, out _)); - Assert.False(CloudBackupPackage.TryParseFileName($"{CloudBackupPackage.FilePrefix}broken.srpart", out _, out _, out _, out _)); - Assert.False(CloudBackupPackage.TryParseFileName(null, out _, out _, out _, out _)); - // A crafted cloud file name must never feed a traversal id into a local staging path. - Assert.False(CloudBackupPackage.TryParseFileName("../escape-manifest.json", out _, out _, out _, out _)); - Assert.False(CloudBackupPackage.TryParseFileName( - $"{CloudBackupPackage.FilePrefix}../escape{CloudBackupPackage.ManifestSuffix}", out _, out _, out _, out _)); - Assert.False(CloudBackupPackage.IsSafeBackupId("..")); - } - - [Fact] - public void MergeAndVerify_RejectsMissingReorderedAndTamperedParts() - { - var archive = CreateBytes(CloudBackupPackage.DefaultPartBytes + 64); - var parts = CloudBackupPackage.Slice(archive, CloudBackupPackage.DefaultPartBytes); - var manifest = CloudBackupPackage.BuildManifest(BackupId, parts, CloudBackupPackage.DefaultPartBytes, - ["list"], DateTime.UtcNow, "v3.0.0", archive); - - Assert.Throws(() => CloudBackupPackage.MergeAndVerify(manifest, [.. parts.Take(1)])); - - var reordered = new List { parts[1], parts[0] }; - Assert.Throws(() => CloudBackupPackage.MergeAndVerify(manifest, reordered)); - - var tampered = parts.ToArray(); - tampered[0][0] ^= 0xFF; - Assert.Throws(() => CloudBackupPackage.MergeAndVerify(manifest, tampered)); - - Assert.Throws(() => CloudBackupPackage.MergeAndVerify(manifest, [[], parts[1]])); - } - - [Fact] - public void ValidateManifest_RejectsUnsupportedFormatAndInconsistentPartNames() - { - var archive = CreateBytes(CloudBackupPackage.DefaultPartBytes + 8); - var parts = CloudBackupPackage.Slice(archive, CloudBackupPackage.DefaultPartBytes); - var manifest = CloudBackupPackage.BuildManifest(BackupId, parts, CloudBackupPackage.DefaultPartBytes, - ["list"], DateTime.UtcNow, "v3.0.0", archive); - - var wrongFormat = Clone(manifest); - wrongFormat.Format = "something-else"; - Assert.Throws(() => CloudBackupPackage.ValidateManifest(wrongFormat)); - - var wrongSchema = Clone(manifest); - wrongSchema.SchemaVersion = CloudBackupPackage.SchemaVersion + 1; - Assert.Throws(() => CloudBackupPackage.ValidateManifest(wrongSchema)); - - var foreignPart = Clone(manifest); - foreignPart.Parts[0].Name = "SecRandom-cloud-other-p01of02.srpart"; - Assert.Throws(() => CloudBackupPackage.ValidateManifest(foreignPart)); - - var wrongLength = Clone(manifest); - wrongLength.ArchiveBytes += 1; - Assert.Throws(() => CloudBackupPackage.ValidateManifest(wrongLength)); - - Assert.Throws(() => CloudBackupPackage.ValidateManifest(null)); - } - - [Fact] - public void ValidateManifest_RejectsArchiveLengthAboveArchiveTransferLimit() - { - var archive = CreateBytes(64); - var parts = CloudBackupPackage.Slice(archive, CloudBackupPackage.DefaultPartBytes); - var manifest = CloudBackupPackage.BuildManifest(BackupId, parts, CloudBackupPackage.DefaultPartBytes, - ["list"], DateTime.UtcNow, "v3.0.0", archive); - manifest.ArchiveBytes = 2L * 1024 * 1024 * 1024; - manifest.Parts[0].Length = manifest.ArchiveBytes; - - Assert.Throws(() => CloudBackupPackage.ValidateManifest(manifest)); - Assert.Throws(() => CloudBackupPackage.MergeAndVerify(manifest, [archive])); - } - - [Fact] - public void ValidateManifest_RejectsInvalidPartSizingAndNullParts() - { - var archive = CreateBytes(64); - var parts = CloudBackupPackage.Slice(archive, CloudBackupPackage.DefaultPartBytes); - var manifest = CloudBackupPackage.BuildManifest(BackupId, parts, CloudBackupPackage.DefaultPartBytes, - ["list"], DateTime.UtcNow, "v3.0.0", archive); - - var zeroPartBytes = Clone(manifest); - zeroPartBytes.PartBytes = 0; - Assert.Throws(() => CloudBackupPackage.ValidateManifest(zeroPartBytes)); - - var oversizedPart = Clone(manifest); - oversizedPart.PartBytes = 1; - Assert.Throws(() => CloudBackupPackage.ValidateManifest(oversizedPart)); - - var nullParts = Clone(manifest); - nullParts.Parts = null!; - Assert.Throws(() => CloudBackupPackage.ValidateManifest(nullParts)); - } - - [Fact] - public void ValidateManifest_RejectsTooManyParts() - { - var archive = CreateBytes(64); - var parts = CloudBackupPackage.Slice(archive, CloudBackupPackage.DefaultPartBytes); - var manifest = CloudBackupPackage.BuildManifest(BackupId, parts, CloudBackupPackage.DefaultPartBytes, - ["list"], DateTime.UtcNow, "v3.0.0", archive); - - for (var index = 0; index < 64; index++) - { - manifest.Parts.Add(new CloudBackupPart - { - Index = manifest.Parts.Count + 1, - Name = CloudBackupPackage.BuildPartName(BackupId, manifest.Parts.Count + 1, 65), - Length = 0, - Sha256 = CloudBackupPackage.Hash([]) - }); - } - - Assert.Throws(() => CloudBackupPackage.ValidateManifest(manifest)); - } - - [Fact] - public void EnsureUploadBodySize_KeepsTheDefaultPartInsideTheRequestBudget() - { - CloudBackupPackage.EnsureUploadBodySize(CloudBackupPackage.DefaultPartBytes); - Assert.Throws(() => CloudBackupPackage.EnsureUploadBodySize(2 * 1024 * 1024)); - } - - [Fact] - public void CreateBackupId_IsUniqueAndSortable() - { - var timestamp = new DateTime(2026, 8, 30, 9, 8, 7, DateTimeKind.Utc); - var first = CloudBackupPackage.CreateBackupId(timestamp); - var second = CloudBackupPackage.CreateBackupId(timestamp); - - Assert.StartsWith("20260830-090807-", first); - Assert.NotEqual(first, second); - Assert.True(CloudBackupPackage.IsCloudBackupFileName(CloudBackupPackage.BuildManifestName(first))); - } - - [Fact] - public void CreateBackupId_WithADeviceTag_RoundTripsThroughTheFileNameAndStaysSafe() - { - var timestamp = new DateTime(2026, 8, 30, 9, 8, 7, DateTimeKind.Utc); - - var backupId = CloudBackupPackage.CreateBackupId(timestamp, "DESKTOP-ABC"); - - Assert.True(CloudBackupPackage.IsSafeBackupId(backupId)); - Assert.True(CloudBackupPackage.TryGetDeviceTag(backupId, out var deviceTag)); - Assert.Equal("DESKTOP-ABC", deviceTag); - - // The tag rides along inside the part and manifest names, so the cloud listing is enough to - // attribute a backup without downloading its manifest. - var manifestName = CloudBackupPackage.BuildManifestName(backupId); - Assert.True(CloudBackupPackage.TryParseFileName(manifestName, out var parsedId, out _, out _, out var isManifest)); - Assert.True(isManifest); - Assert.Equal(backupId, parsedId); - Assert.True(CloudBackupPackage.TryGetDeviceTag(parsedId, out var parsedTag)); - Assert.Equal("DESKTOP-ABC", parsedTag); - - var partName = CloudBackupPackage.BuildPartName(backupId, 1, 2); - Assert.True(CloudBackupPackage.TryParseFileName(partName, out var partId, out var partIndex, out var partCount, out _)); - Assert.Equal(backupId, partId); - Assert.Equal(1, partIndex); - Assert.Equal(2, partCount); - } - - [Fact] - public void CreateBackupId_WithoutADeviceTag_CarriesNoTag() - { - var backupId = CloudBackupPackage.CreateBackupId(new DateTime(2026, 8, 30, 9, 8, 7, DateTimeKind.Utc)); - - Assert.False(CloudBackupPackage.TryGetDeviceTag(backupId, out var deviceTag)); - Assert.Equal(string.Empty, deviceTag); - } - - [Fact] - public void BuildDeviceTag_KeepsSafeCharactersAndCapsTheLength() - { - Assert.Equal("DESKTOP-ABC", CloudBackupPackage.BuildDeviceTag(" DESKTOP-ABC ")); - // Unsafe characters are dropped rather than replaced, so a fully non-ASCII name still reaches - // the digest fallback instead of turning into a row of dashes. - Assert.Equal("homepc", CloudBackupPackage.BuildDeviceTag("home pc!")); - - var capped = CloudBackupPackage.BuildDeviceTag("abcdefghijklmnopqrstuvwxyz"); - Assert.Equal(CloudBackupPackage.MaxDeviceTagLength, capped.Length); - Assert.Equal("abcdefghijklmnop", capped); - } - - [Fact] - public void BuildDeviceTag_FallsBackToAStableDigestWhenNothingIsAsciiSafe() - { - var first = CloudBackupPackage.BuildDeviceTag("教室电脑"); - var second = CloudBackupPackage.BuildDeviceTag("教室电脑"); - - Assert.Equal(4, first.Length); - Assert.Equal(first, second); - Assert.True(CloudBackupPackage.IsSafeBackupId(CloudBackupPackage.CreateBackupId(DateTime.UtcNow, first))); - Assert.Equal(string.Empty, CloudBackupPackage.BuildDeviceTag("")); - } - - [Fact] - public void TryGetDeviceTag_ReportsNoTagForForeignIds() - { - Assert.False(CloudBackupPackage.TryGetDeviceTag("20260830-120000-abcd1234", out _)); - // An id an older build uploaded, and one crafted through the cloud dashboard, are both foreign: - // neither may be attributed to a device. - Assert.False(CloudBackupPackage.TryGetDeviceTag("20260830-120000-abcd1234_", out _)); - Assert.False(CloudBackupPackage.TryGetDeviceTag("holiday_photos", out _)); - Assert.False(CloudBackupPackage.TryGetDeviceTag("20260830-120000-abcd123456", out _)); - Assert.False(CloudBackupPackage.TryGetDeviceTag(null, out _)); - } - - private static CloudBackupManifest Clone(CloudBackupManifest manifest) => - CloudBackupPackage.DeserializeManifest(CloudBackupPackage.SerializeManifest(manifest)); - - private static byte[] CreateBytes(int length) - { - var bytes = new byte[length]; - RandomNumberGenerator.Fill(bytes); - return bytes; - } -} diff --git a/SecRandom.Core.Tests/CloudBackupServiceTests.cs b/SecRandom.Core.Tests/CloudBackupServiceTests.cs deleted file mode 100644 index 2eda80c88..000000000 --- a/SecRandom.Core.Tests/CloudBackupServiceTests.cs +++ /dev/null @@ -1,715 +0,0 @@ -using System.Net; -using System.Reflection; -using System.Text; -using System.Text.Json; -using System.Text.Json.Nodes; -using Microsoft.Extensions.Logging.Abstractions; -using SecRandom.Core.Abstraction; -using SecRandom.Core.Models; -using SecRandom.Core.Services.Archive; -using SecRandom.Core.Services.Config; -using SecRandom.Services.Auth; -using SecRandom.Services.Config; -using SecRandom.Services.ImportExport; -using SecRandom.Shared; - -namespace SecRandom.Core.Tests; - -public sealed class CloudBackupServiceTests : IDisposable -{ - private const string ClientId = SectlAuthService.ClientId; - - private readonly string _dataRoot = Path.Combine(Path.GetTempPath(), "SecRandom", "cloud-backup-tests", Guid.NewGuid().ToString("N")); - - public CloudBackupServiceTests() - { - ResetDataRootForTests(); - ConfigureDataRootForTests(_dataRoot); - } - - [Fact] - public async Task UploadAsync_UploadsPartsBeforeTheManifestAndReportsProgress() - { - var uploadedNames = new List(); - var archive = CreateArchiveBytes(CloudBackupPackage.DefaultPartBytes + 11); - var handler = new RecordingHandler(request => - { - if (request.RequestUri!.AbsolutePath.EndsWith("/upload", StringComparison.Ordinal)) - { - uploadedNames.Add(ReadUploadedName(request)); - return Json("{\"success\":true,\"file_id\":\"file-1\",\"filename\":\"part.srpart\",\"size\":1}"); - } - - throw new InvalidOperationException($"Unexpected request: {request.Method} {request.RequestUri}"); - }); - var service = CreateService(handler, archive); - var progress = new List(); - - var descriptor = await service.UploadAsync(new ProgressRecorder(progress), TestContext.Current.CancellationToken); - - Assert.Equal(3, uploadedNames.Count); - Assert.EndsWith($"{CloudBackupPackage.ManifestSuffix}", uploadedNames[3 - 1]); - Assert.Contains("-p01of02", uploadedNames[0]); - Assert.Contains("-p02of02", uploadedNames[1]); - Assert.True(descriptor.IsComplete); - Assert.Equal(2, descriptor.PartCount); - Assert.Equal(archive.LongLength, descriptor.TotalBytes); - Assert.Equal([1, 2, 3], progress.Select(item => item.Completed)); - Assert.Equal(CloudBackupProgress.DoneStage, progress[^1].Stage); - Assert.False(File.Exists(Path.Combine(_dataRoot, "cache", "cloud-backup", $"{descriptor.BackupId}.zip"))); - } - - [Fact] - public async Task UploadAsync_WhenAPartUploadFails_RollsBackTheUploadedParts() - { - var deleted = new List(); - var attempts = 0; - var archive = CreateArchiveBytes(CloudBackupPackage.DefaultPartBytes * 2 + 11); - var handler = new RecordingHandler(request => - { - if (request.RequestUri!.AbsolutePath.EndsWith("/upload", StringComparison.Ordinal)) - { - attempts++; - if (attempts == 3) - return Json("{\"error\":\"storage_exceeded\",\"error_description\":\"Storage quota exceeded\"}", HttpStatusCode.RequestEntityTooLarge); - return Json($"{{\"success\":true,\"file_id\":\"file-{attempts}\",\"filename\":\"part.srpart\",\"size\":1}}"); - } - - if (request.Method == HttpMethod.Delete) - { - deleted.Add(request.RequestUri.AbsolutePath); - return Json("{\"success\":true}"); - } - - throw new InvalidOperationException($"Unexpected request: {request.Method} {request.RequestUri}"); - }); - var service = CreateService(handler, archive); - - var exception = await Assert.ThrowsAsync(() => - service.UploadAsync(cancellationToken: TestContext.Current.CancellationToken)); - - Assert.Equal("storage_exceeded", exception.Code); - Assert.Equal(["/api/cloud/files/file-1", "/api/cloud/files/file-2"], deleted); - } - - [Fact] - public async Task ListAsync_GroupsPartsWithTheirManifestAndFlagsIncompleteBackups() - { - var handler = new RecordingHandler(_ => Json(BuildListResponse( - ("f-manifest", $"{CloudBackupPackage.FilePrefix}20260830-120000-aaaa0001{CloudBackupPackage.ManifestSuffix}", 20), - ("f-part-1", CloudBackupPackage.BuildPartName("20260830-120000-aaaa0001", 1, 2), 100), - ("f-part-2", CloudBackupPackage.BuildPartName("20260830-120000-aaaa0001", 2, 2), 50), - ("f-orphan", CloudBackupPackage.BuildPartName("20260830-130000-bbbb0002", 1, 2), 70), - ("f-foreign", "holiday-photo.png", 999)))); - var service = CreateService(handler); - - var backups = await service.ListAsync(TestContext.Current.CancellationToken); - - Assert.Equal(2, backups.Count); - var complete = backups.Single(item => item.BackupId == "20260830-120000-aaaa0001"); - Assert.True(complete.IsComplete); - Assert.True(complete.CanRestore); - Assert.Equal(150, complete.TotalBytes); - Assert.Equal(2, complete.PartCount); - Assert.Equal("f-manifest", complete.ManifestFileId); - - var incomplete = backups.Single(item => item.BackupId == "20260830-130000-bbbb0002"); - Assert.False(incomplete.IsComplete); - Assert.False(incomplete.CanRestore); - Assert.Equal(70, incomplete.TotalBytes); - } - - [Fact] - public async Task DownloadAsync_RejectsAnIncompleteBackupWithoutAnyRequest() - { - var requests = 0; - var handler = new RecordingHandler(_ => - { - requests++; - return Json("{}"); - }); - var service = CreateService(handler); - var descriptor = new CloudBackupDescriptor("20260830-120000-aaaa0001", "name", DateTimeOffset.UtcNow, 10, 1, false, null); - - await Assert.ThrowsAsync(() => - service.DownloadAsync(descriptor, TestContext.Current.CancellationToken)); - Assert.Equal(0, requests); - } - - [Fact] - public async Task DownloadAsync_VerifiesEachPartAndWritesTheRebuiltArchive() - { - var archive = CreateArchiveBytes(CloudBackupPackage.DefaultPartBytes + 37); - var parts = CloudBackupPackage.Slice(archive, CloudBackupPackage.DefaultPartBytes); - var backupId = "20260830-120000-aaaa0001"; - var manifest = CloudBackupPackage.BuildManifest(backupId, parts, CloudBackupPackage.DefaultPartBytes, - DataArchiveService.CloudBackupRoots, DateTimeOffset.UtcNow.UtcDateTime, "v3.0.0", archive); - var manifestName = CloudBackupPackage.BuildManifestName(backupId); - var manifestBytes = CloudBackupPackage.SerializeManifest(manifest); - var handler = new RecordingHandler(request => Download(request, new Dictionary - { - ["f-manifest"] = manifestBytes, - ["f-part-1"] = parts[0], - ["f-part-2"] = parts[1] - })); - var service = CreateService(handler); - handler.Files = BuildListResponse( - ("f-manifest", manifestName, manifestBytes.Length), - ("f-part-1", manifest.Parts[0].Name, parts[0].Length), - ("f-part-2", manifest.Parts[1].Name, parts[1].Length)); - var descriptor = new CloudBackupDescriptor(backupId, manifestName, DateTimeOffset.UtcNow, - archive.LongLength, 2, true, "f-manifest"); - - var path = await service.DownloadAsync(descriptor, TestContext.Current.CancellationToken); - - Assert.Equal(archive, await File.ReadAllBytesAsync(path, TestContext.Current.CancellationToken)); - } - - [Fact] - public async Task DownloadAsync_RejectsATamperedPartBeforeWritingALocalArchive() - { - var archive = CreateArchiveBytes(CloudBackupPackage.DefaultPartBytes + 37); - var parts = CloudBackupPackage.Slice(archive, CloudBackupPackage.DefaultPartBytes); - var backupId = "20260830-120000-aaaa0001"; - var manifest = CloudBackupPackage.BuildManifest(backupId, parts, CloudBackupPackage.DefaultPartBytes, - DataArchiveService.CloudBackupRoots, DateTimeOffset.UtcNow.UtcDateTime, "v3.0.0", archive); - var tampered = (byte[])parts[1].Clone(); - tampered[0] ^= 0xFF; - var handler = new RecordingHandler(request => Download(request, new Dictionary - { - ["f-manifest"] = CloudBackupPackage.SerializeManifest(manifest), - ["f-part-1"] = parts[0], - ["f-part-2"] = tampered - })); - var service = CreateService(handler); - handler.Files = BuildListResponse( - ("f-manifest", CloudBackupPackage.BuildManifestName(backupId), 100), - ("f-part-1", manifest.Parts[0].Name, parts[0].Length), - ("f-part-2", manifest.Parts[1].Name, parts[1].Length)); - var descriptor = new CloudBackupDescriptor(backupId, "name", DateTimeOffset.UtcNow, - archive.LongLength, 2, true, "f-manifest"); - - await Assert.ThrowsAsync(() => - service.DownloadAsync(descriptor, TestContext.Current.CancellationToken)); - - Assert.False(File.Exists(Path.Combine(_dataRoot, "cache", "cloud-backup", $"{backupId}.zip"))); - } - - [Fact] - public async Task DeleteAsync_DeletesPartsBeforeTheManifest() - { - var operations = new List(); - var backupId = "20260830-120000-aaaa0001"; - var handler = new RecordingHandler(request => - { - if (request.Method == HttpMethod.Delete) - { - operations.Add(request.RequestUri!.AbsolutePath); - return Json("{\"success\":true}"); - } - - return Json(BuildListResponse( - ("f-manifest", CloudBackupPackage.BuildManifestName(backupId), 10), - ("f-part-1", CloudBackupPackage.BuildPartName(backupId, 1, 2), 10), - ("f-part-2", CloudBackupPackage.BuildPartName(backupId, 2, 2), 10))); - }); - var service = CreateService(handler); - var descriptor = new CloudBackupDescriptor(backupId, "name", DateTimeOffset.UtcNow, 20, 2, true, "f-manifest"); - - await service.DeleteAsync(descriptor, TestContext.Current.CancellationToken); - - Assert.Equal([ - "/api/cloud/files/f-part-1", "/api/cloud/files/f-part-2", "/api/cloud/files/f-manifest" - ], operations); - } - - [Fact] - public async Task DeleteAsync_WhenAPartDeleteFails_KeepsTheManifestSoTheBackupStaysVisible() - { - var operations = new List(); - var backupId = "20260830-120000-aaaa0001"; - var handler = new RecordingHandler(request => - { - if (request.Method == HttpMethod.Delete) - { - operations.Add(request.RequestUri!.AbsolutePath); - return request.RequestUri.AbsolutePath.EndsWith("f-part-1", StringComparison.Ordinal) - ? Json("{\"error\":\"internal_error\",\"error_description\":\"boom\"}", HttpStatusCode.InternalServerError) - : Json("{\"success\":true}"); - } - - return Json(BuildListResponse( - ("f-manifest", CloudBackupPackage.BuildManifestName(backupId), 10), - ("f-part-1", CloudBackupPackage.BuildPartName(backupId, 1, 2), 10), - ("f-part-2", CloudBackupPackage.BuildPartName(backupId, 2, 2), 10))); - }); - var service = CreateService(handler); - var descriptor = new CloudBackupDescriptor(backupId, "name", DateTimeOffset.UtcNow, 20, 2, true, "f-manifest"); - - var exception = await Assert.ThrowsAsync(() => - service.DeleteAsync(descriptor, TestContext.Current.CancellationToken)); - - Assert.Equal("delete_failed", exception.Code); - Assert.DoesNotContain("/api/cloud/files/f-manifest", operations); - } - - [Fact] - public async Task PurgeIncompleteAsync_RemovesOnlyBackupsWithoutTheirManifest() - { - var deleted = new List(); - var completeId = "20260830-120000-aaaa0001"; - var incompleteId = "20260830-130000-bbbb0002"; - var handler = new RecordingHandler(request => - { - if (request.Method == HttpMethod.Delete) - { - deleted.Add(request.RequestUri!.AbsolutePath); - return Json("{\"success\":true}"); - } - - return Json(BuildListResponse( - ("f-manifest", CloudBackupPackage.BuildManifestName(completeId), 10), - ("f-part-1", CloudBackupPackage.BuildPartName(completeId, 1, 1), 10), - ("f-orphan", CloudBackupPackage.BuildPartName(incompleteId, 1, 2), 10))); - }); - var service = CreateService(handler); - - var removed = await service.PurgeIncompleteAsync(TestContext.Current.CancellationToken); - - Assert.Equal(1, removed); - Assert.Equal(["/api/cloud/files/f-orphan"], deleted); - } - - [Fact] - public async Task UploadAutomaticAsync_WhenTheQuotaIsExhausted_DeletesTheOldestBackupAndRetries() - { - var deleted = new List(); - var files = new List<(string FileId, string FileName, long Size)>(); - files.AddRange(BuildBackupFiles("20260801-120000-aaaa0001")); - files.AddRange(BuildBackupFiles("20260820-120000-bbbb0002")); - var uploads = 0; - var handler = new RecordingHandler(request => - { - var path = request.RequestUri!.AbsolutePath; - if (path.EndsWith("/upload", StringComparison.Ordinal)) - { - uploads++; - return uploads == 1 - ? Json("{\"error\":\"storage_exceeded\",\"error_description\":\"Storage quota exceeded\"}", - HttpStatusCode.RequestEntityTooLarge) - : Json($"{{\"success\":true,\"file_id\":\"new-{uploads}\",\"filename\":\"part.srpart\",\"size\":1}}"); - } - - if (request.Method == HttpMethod.Delete) - { - deleted.Add(path); - files.RemoveAll(file => path.EndsWith(file.FileId, StringComparison.Ordinal)); - return Json("{\"success\":true}"); - } - - if (request.Method == HttpMethod.Get && path.EndsWith("/api/cloud/files", StringComparison.Ordinal)) - return Json(BuildListResponse(files.ToArray())); - - throw new InvalidOperationException($"Unexpected request: {request.Method} {request.RequestUri}"); - }); - var service = CreateService(handler, CreateArchiveBytes(CloudBackupPackage.DefaultPartBytes)); - - var descriptor = await service.UploadAutomaticAsync(0, cancellationToken: TestContext.Current.CancellationToken); - - Assert.True(descriptor.IsComplete); - Assert.Equal(3, uploads); - Assert.Equal([ - "/api/cloud/files/f-20260801-120000-aaaa0001-p1", - "/api/cloud/files/f-20260801-120000-aaaa0001-m" - ], deleted); - Assert.Equal(2, files.Count); - Assert.All(files, file => Assert.Contains("20260820-120000-bbbb0002", file.FileId)); - } - - [Fact] - public async Task UploadAutomaticAsync_WhenTheQuotaIsExhaustedAndNothingIsLeft_SurfacesTheQuotaError() - { - var handler = new RecordingHandler(request => - { - if (request.RequestUri!.AbsolutePath.EndsWith("/upload", StringComparison.Ordinal)) - return Json("{\"error\":\"storage_exceeded\",\"error_description\":\"Storage quota exceeded\"}", - HttpStatusCode.RequestEntityTooLarge); - if (request.Method == HttpMethod.Get) - return Json(BuildListResponse()); - throw new InvalidOperationException($"Unexpected request: {request.Method} {request.RequestUri}"); - }); - var service = CreateService(handler, CreateArchiveBytes(CloudBackupPackage.DefaultPartBytes)); - - var exception = await Assert.ThrowsAsync(() => - service.UploadAutomaticAsync(0, cancellationToken: TestContext.Current.CancellationToken)); - - Assert.Equal("storage_exceeded", exception.Code); - } - - [Fact] - public async Task UploadAutomaticAsync_WhenOwnBackupsExceedTheRetentionLimit_KeepsAnotherDevicesBackups() - { - var deleted = new List(); - var files = new List<(string FileId, string FileName, long Size)>(); - files.AddRange(BuildBackupFiles("20260801-120000-aaaa0001_dev-a")); - files.AddRange(BuildBackupFiles("20260810-120000-bbbb0002_dev-a")); - files.AddRange(BuildBackupFiles("20260820-120000-cccc0003_dev-a")); - files.AddRange(BuildBackupFiles("20260805-120000-dddd0004_dev-b")); - files.AddRange(BuildBackupFiles("20260815-120000-eeee0005_dev-b")); - var handler = new RecordingHandler(request => - { - var path = request.RequestUri!.AbsolutePath; - if (path.EndsWith("/upload", StringComparison.Ordinal)) - return Json("{\"success\":true,\"file_id\":\"new-1\",\"filename\":\"part.srpart\",\"size\":1}"); - if (request.Method == HttpMethod.Delete) - { - deleted.Add(path); - files.RemoveAll(file => path.EndsWith(file.FileId, StringComparison.Ordinal)); - return Json("{\"success\":true}"); - } - - if (request.Method == HttpMethod.Get && path.EndsWith("/api/cloud/files", StringComparison.Ordinal)) - return Json(BuildListResponse(files.ToArray())); - - throw new InvalidOperationException($"Unexpected request: {request.Method} {request.RequestUri}"); - }); - var service = CreateService(handler, CreateArchiveBytes(CloudBackupPackage.DefaultPartBytes), "dev-a"); - - await service.UploadAutomaticAsync(1, cancellationToken: TestContext.Current.CancellationToken); - - // Only this device's surplus is trimmed, oldest first, so dev-b keeps both of its backups. - Assert.Equal([ - "/api/cloud/files/f-20260810-120000-bbbb0002_dev-a-p1", - "/api/cloud/files/f-20260810-120000-bbbb0002_dev-a-m", - "/api/cloud/files/f-20260801-120000-aaaa0001_dev-a-p1", - "/api/cloud/files/f-20260801-120000-aaaa0001_dev-a-m" - ], deleted); - Assert.Equal([ - "f-20260820-120000-cccc0003_dev-a-p1", - "f-20260820-120000-cccc0003_dev-a-m", - "f-20260805-120000-dddd0004_dev-b-p1", - "f-20260805-120000-dddd0004_dev-b-m", - "f-20260815-120000-eeee0005_dev-b-p1", - "f-20260815-120000-eeee0005_dev-b-m" - ], files.Select(file => file.FileId)); - } - - [Fact] - public async Task UploadAsync_StampsTheDeviceAliasIntoEveryCloudFileName() - { - var uploadedNames = new List(); - var handler = new RecordingHandler(request => - { - if (request.RequestUri!.AbsolutePath.EndsWith("/upload", StringComparison.Ordinal)) - { - uploadedNames.Add(ReadUploadedName(request)); - return Json("{\"success\":true,\"file_id\":\"file-1\",\"filename\":\"part.srpart\",\"size\":1}"); - } - - throw new InvalidOperationException($"Unexpected request: {request.Method} {request.RequestUri}"); - }); - var service = CreateService(handler, CreateArchiveBytes(CloudBackupPackage.DefaultPartBytes), "dev-a"); - - var descriptor = await service.UploadAsync(cancellationToken: TestContext.Current.CancellationToken); - - Assert.Equal("dev-a", descriptor.DeviceTag); - Assert.True(CloudBackupPackage.TryGetDeviceTag(descriptor.BackupId, out var deviceTag)); - Assert.Equal("dev-a", deviceTag); - Assert.Equal(2, uploadedNames.Count); - Assert.All(uploadedNames, name => Assert.Contains("_dev-a", name, StringComparison.Ordinal)); - } - - [Fact] - public async Task ListAsync_ExposesTheDeviceAliasAndKeepsUntaggedBackupsUsable() - { - var handler = new RecordingHandler(_ => Json(BuildListResponse( - ("f-tagged-m", CloudBackupPackage.BuildManifestName("20260810-120000-bbbb0002_dev-a"), 10), - ("f-tagged-p", CloudBackupPackage.BuildPartName("20260810-120000-bbbb0002_dev-a", 1, 1), 10), - ("f-legacy-m", CloudBackupPackage.BuildManifestName("20260801-120000-aaaa0001"), 10), - ("f-legacy-p", CloudBackupPackage.BuildPartName("20260801-120000-aaaa0001", 1, 1), 10)))); - var service = CreateService(handler); - - var backups = await service.ListAsync(TestContext.Current.CancellationToken); - - var tagged = backups.Single(item => item.BackupId == "20260810-120000-bbbb0002_dev-a"); - Assert.Equal("dev-a", tagged.DeviceTag); - Assert.Equal("20260810-120000-bbbb0002_dev-a (dev-a)", tagged.DisplayName); - - // A backup uploaded before device aliases existed stays listable and restorable; it is merely - // never attributed to a device, so retention never deletes it implicitly. - var legacy = backups.Single(item => item.BackupId == "20260801-120000-aaaa0001"); - Assert.Equal(string.Empty, legacy.DeviceTag); - Assert.Equal("20260801-120000-aaaa0001", legacy.DisplayName); - Assert.True(legacy.CanRestore); - } - - [Fact] - public async Task ListAsync_MarksABackupFromTheRemovedEncryptionFeatureAsUnrestorable() - { - const string encryptedId = "20260805-120000-eeee0005"; - var handler = new RecordingHandler(_ => Json(BuildListResponse( - ("f-enc-m", $"{CloudBackupPackage.FilePrefix}{encryptedId}{CloudBackupPackage.LegacyEncryptionMarker}{CloudBackupPackage.ManifestSuffix}", 10), - ("f-enc-p", $"{CloudBackupPackage.FilePrefix}{encryptedId}-p01of01{CloudBackupPackage.LegacyEncryptionMarker}{CloudBackupPackage.PartExtension}", 10)))); - var service = CreateService(handler); - - var backups = await service.ListAsync(TestContext.Current.CancellationToken); - - // The package is complete on the wire, but its passphrase key is gone with the feature, so it - // stays visible (the user can still delete it) while never being offered as restorable. - var legacy = backups.Single(); - Assert.Equal(encryptedId, legacy.BackupId); - Assert.True(legacy.IsComplete); - Assert.True(legacy.IsEncrypted); - Assert.False(legacy.CanRestore); - } - - [Fact] - public async Task DownloadAsync_RefusesALegacyEncryptedBackupWithoutAnyRequest() - { - const string encryptedId = "20260805-120000-eeee0005"; - var requests = 0; - var handler = new RecordingHandler(_ => - { - requests++; - return Json("{}"); - }); - var service = CreateService(handler); - var descriptor = new CloudBackupDescriptor(encryptedId, encryptedId, DateTimeOffset.UtcNow, 10, 1, true, - "f-enc-m", string.Empty, IsEncrypted: true); - - await Assert.ThrowsAsync(() => - service.DownloadAsync(descriptor, TestContext.Current.CancellationToken)); - - Assert.Equal(0, requests); - } - - [Fact] - public async Task GetLatestOwnBackupTimeAsync_CountsOnlyThisDevicesUploads() - { - var handler = new RecordingHandler(_ => Json(BuildListResponse( - ("f-other-p", CloudBackupPackage.BuildPartName("20260820-120000-cccc0003_dev-b", 1, 1), 10), - ("f-other-m", CloudBackupPackage.BuildManifestName("20260820-120000-cccc0003_dev-b"), 10)))); - - var otherOnly = CreateService(handler, deviceAlias: "dev-a"); - var ownDevice = CreateService(handler, deviceAlias: "dev-b"); - - // dev-a has not uploaded yet, even though the account holds dev-b's newer backup. - Assert.Null(await otherOnly.GetLatestOwnBackupTimeAsync(TestContext.Current.CancellationToken)); - // The same listing does decide dev-b's cadence, so the filter is the alias rather than "no data". - Assert.Equal(new DateTimeOffset(2026, 8, 30, 12, 0, 0, TimeSpan.Zero), - await ownDevice.GetLatestOwnBackupTimeAsync(TestContext.Current.CancellationToken)); - } - - [Fact] - public async Task UploadAutomaticAsync_WhenItSucceeds_AnnouncesTheUpload() - { - var announced = 0; - var handler = new RecordingHandler(request => - { - var path = request.RequestUri!.AbsolutePath; - if (path.EndsWith("/upload", StringComparison.Ordinal)) - return Json("{\"success\":true,\"file_id\":\"new-1\",\"filename\":\"part.srpart\",\"size\":1}"); - if (request.Method == HttpMethod.Get && path.EndsWith("/api/cloud/files", StringComparison.Ordinal)) - return Json(BuildListResponse()); - throw new InvalidOperationException($"Unexpected request: {request.Method} {request.RequestUri}"); - }); - var service = CreateService(handler, CreateArchiveBytes(CloudBackupPackage.DefaultPartBytes)); - service.AutomaticBackupUploaded += (_, _) => announced++; - - await service.UploadAutomaticAsync(0, cancellationToken: TestContext.Current.CancellationToken); - - Assert.Equal(1, announced); - } - - public void Dispose() - { - ResetDataRootForTests(); - if (Directory.Exists(_dataRoot)) - Directory.Delete(_dataRoot, recursive: true); - } - - private CloudBackupService CreateService(RecordingHandler handler, byte[]? archive = null, string deviceAlias = "") - { - var httpClient = new HttpClient(handler) { BaseAddress = new Uri("https://appwrite.sectl.cn/") }; - var factory = new StubHttpClientFactory(httpClient); - var config = new MainConfigModel(); - config.General.Backup.CloudDeviceAlias = deviceAlias; - var configHandler = new MainConfigHandler( - NullLogger.Instance, - new TestConfigService(config)); - var deviceUuidStore = new DeviceUuidStore(configHandler, NullLogger.Instance); - var authService = new SectlAuthService(TestTokenStore.Create(), factory, deviceUuidStore, - NullLogger.Instance, new LoopbackAuthRedirectBrokerFactory()); - SetToken(authService, new SectlToken("access-token", "refresh-token", "user-1", 3600)); - var cloudClient = new SectlCloudStorageClient(authService, factory, NullLogger.Instance); - return new CloudBackupService(authService, cloudClient, configHandler, new FakeImportExportService(archive ?? []), - NullLogger.Instance); - } - - private static HttpResponseMessage Download(HttpRequestMessage request, IReadOnlyDictionary content) - { - var path = request.RequestUri!.AbsolutePath; - if (path.EndsWith("/download", StringComparison.Ordinal)) - { - var fileId = path.Split('/')[4]; - return Json($"{{\"download_url\":\"https://storage.example/{fileId}\"}}"); - } - - var identifier = request.RequestUri.AbsolutePath.TrimStart('/'); - return content.TryGetValue(identifier, out var bytes) - ? new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent(bytes) } - : new HttpResponseMessage(HttpStatusCode.NotFound); - } - - private static string ReadUploadedName(HttpRequestMessage request) - { - var body = request.Content!.ReadAsStringAsync().GetAwaiter().GetResult(); - return JsonNode.Parse(body)!["file"]!["name"]!.GetValue(); - } - - /// Decodes one uploaded part or manifest back to the bytes the cloud would store. - private static byte[] ReadUploadedBytes(HttpRequestMessage request) - { - var body = request.Content!.ReadAsStringAsync().GetAwaiter().GetResult(); - var data = JsonNode.Parse(body)!["file"]!["data"]!.GetValue(); - var separator = data.IndexOf("base64,", StringComparison.Ordinal); - return Convert.FromBase64String(data[(separator + "base64,".Length)..]); - } - - private static string BuildListResponse(params (string FileId, string FileName, long Size)[] files) - { - var payload = new JsonObject - { - ["files"] = new JsonArray(files.Select(file => new JsonObject - { - ["file_id"] = file.FileId, - ["filename"] = file.FileName, - ["size"] = file.Size, - ["created_at"] = "2026-08-30T12:00:00Z" - }).ToArray()), - ["has_more"] = false - }; - return payload.ToJsonString(); - } - - /// One complete cloud backup as the listing reports it: a single part plus its manifest. - private static IEnumerable<(string FileId, string FileName, long Size)> BuildBackupFiles(string backupId) => - [ - ($"f-{backupId}-p1", CloudBackupPackage.BuildPartName(backupId, 1, 1), 10), - ($"f-{backupId}-m", CloudBackupPackage.BuildManifestName(backupId), 10) - ]; - - private static void SetToken(SectlAuthService service, SectlToken token) - { - var field = typeof(SectlAuthService).GetField("_token", BindingFlags.Instance | BindingFlags.NonPublic); - Assert.NotNull(field); - field!.SetValue(service, token); - } - - private static byte[] CreateArchiveBytes(int length) - { - var bytes = new byte[length]; - System.Security.Cryptography.RandomNumberGenerator.Fill(bytes); - return bytes; - } - - private static void ConfigureDataRootForTests(string dataRoot) - { - GetUtilsMethod("ConfigureDataRoot").Invoke(null, [dataRoot]); - } - - private static void ResetDataRootForTests() - { - GetUtilsMethod("ResetDataRootForTests").Invoke(null, null); - } - - private static MethodInfo GetUtilsMethod(string name) - { - return typeof(Utils).GetMethod(name, BindingFlags.Static | BindingFlags.NonPublic) - ?? throw new InvalidOperationException($"Utils.{name} was not found."); - } - - private static HttpResponseMessage Json(string body, HttpStatusCode status = HttpStatusCode.OK) => new(status) - { - Content = new StringContent(body, Encoding.UTF8, "application/json") - }; - - private sealed class ProgressRecorder(List progress) : IProgress - { - public void Report(CloudBackupProgress value) => progress.Add(value); - } - - private sealed class RecordingHandler(Func send) : HttpMessageHandler - { - public string? Files { get; set; } - - protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) - { - if (Files is not null - && request.Method == HttpMethod.Get - && request.RequestUri!.AbsolutePath.EndsWith("/api/cloud/files", StringComparison.Ordinal)) - return Task.FromResult(Json(Files)); - - return Task.FromResult(send(request)); - } - } - - private sealed class StubHttpClientFactory(HttpClient client) : IHttpClientFactory - { - public HttpClient CreateClient(string name) => client; - } - - private sealed class FakeImportExportService(byte[] archive) : IImportExportService - { - public IReadOnlyList GetCloudBackupRoots() => DataArchiveService.CloudBackupRoots; - - public Task ExportCloudBackupAsync(string destinationPath, CancellationToken cancellationToken = default) - { - Directory.CreateDirectory(Path.GetDirectoryName(destinationPath)!); - File.WriteAllBytes(destinationPath, archive); - return Task.FromResult(destinationPath); - } - - public Task ExportDiagnosticAsync(string destinationPath, bool includeExtendedData = false, - CancellationToken cancellationToken = default) => throw new NotSupportedException(); - - public Task ExportSettingsAsync(string destinationPath, CancellationToken cancellationToken = default) => - throw new NotSupportedException(); - - public Task ExportAllDataAsync(string destinationPath, CancellationToken cancellationToken = default) => - throw new NotSupportedException(); - - public Task InspectSettingsAsync(string sourcePath, CancellationToken cancellationToken = default) => - throw new NotSupportedException(); - - public Task InspectAllDataAsync(string sourcePath, CancellationToken cancellationToken = default) => - throw new NotSupportedException(); - - public Task InspectCloudBackupAsync(string sourcePath, CancellationToken cancellationToken = default) => - throw new NotSupportedException(); - - public Task ImportSettingsAsync(string sourcePath, CancellationToken cancellationToken = default) => - throw new NotSupportedException(); - - public Task ImportAllDataAsync(string sourcePath, CancellationToken cancellationToken = default) => - throw new NotSupportedException(); - - public Task ImportCloudBackupAsync(string sourcePath, CancellationToken cancellationToken = default) => - throw new NotSupportedException(); - - public string CreateManualBackup(IReadOnlyCollection roots) => throw new NotSupportedException(); - - public string CreateAutomaticBackup(CancellationToken cancellationToken = default) => throw new NotSupportedException(); - - public Task RestoreBackupAsync(string sourcePath, CancellationToken cancellationToken = default) => - throw new NotSupportedException(); - } - - private sealed class TestConfigService(MainConfigModel config) : ConfigServiceBase - { - public override bool IsConfigExists(T fallback) => true; - public override T LoadConfig(T fallback) => config is T typed ? typed : fallback; - public override void SaveConfig(T value) { } - public override void DeleteConfig(T value) { } - } -} diff --git a/SecRandom.Core.Tests/DataArchiveServiceTests.cs b/SecRandom.Core.Tests/DataArchiveServiceTests.cs index 0b2f39f36..d5737d3da 100644 --- a/SecRandom.Core.Tests/DataArchiveServiceTests.cs +++ b/SecRandom.Core.Tests/DataArchiveServiceTests.cs @@ -93,11 +93,6 @@ public async Task ExportAllData_NeverCarriesTheSecurityDirectory() var paths = ReadManifestPaths(destination); Assert.DoesNotContain(paths, path => path.StartsWith("config/security", StringComparison.OrdinalIgnoreCase)); - - // 云备份的上限里同样没有这个目录 - var cloudRoots = DataArchiveService.ResolveCloudBackupRoots( - provider.GetRequiredService().Data.General.Backup); - Assert.DoesNotContain(cloudRoots, root => root.StartsWith("config/security", StringComparison.OrdinalIgnoreCase)); } [Fact] @@ -143,7 +138,7 @@ public async Task ExportAllData_WritesManifestWithMatchingHashesAndLengths() Assert.Equal(GlobalConstants.Version, manifest.ProducerVersion); Assert.Contains(manifest.Files, file => file.Path == "config/settings.json"); Assert.Contains(manifest.Files, file => file.Path == "list/roll_call_list/class.json"); - Assert.Contains(manifest.Files, file => file.Path.StartsWith("history/roll_call_history/", StringComparison.Ordinal)); + Assert.Contains(manifest.Files, file => file.Path.StartsWith("history/roll_call_history/", StringComparison.Ordinal)); var dataEntries = zip.Entries.Where(entry => !string.IsNullOrEmpty(entry.Name) && entry.FullName != "manifest.json").ToList(); Assert.Equal(manifest.Files.Count, dataEntries.Count); @@ -509,182 +504,21 @@ public void CommitCandidate_RollsBackCommittedRootsWhenALaterRootFails() } [Fact] - public async Task ExportCloudBackup_ExcludesDeviceIdentityVoiceCacheLogsAndPlugins() - { - using var provider = CreateProvider(); - var config = provider.GetRequiredService(); - config.Data.General.Backup.CloudIncludeAudio = true; - // The local selection may include logs, audio, and configuration with the device identity; - // none of those may leak into a cloud archive. - config.Data.General.Backup.IncludeLogs = true; - config.Data.General.Backup.IncludeAudio = true; - config.Data.General.Backup.IncludeConfig = true; - config.Save(); - File.WriteAllText(Utils.GetFilePath("config", "device-uuid.json"), "{\"device_uuid\":\"device-1\"}"); - File.WriteAllText(Utils.GetFilePath("list", "roll_call_list", "class.json"), "{}"); - File.WriteAllText(Utils.GetFilePath("history", "roll_call_history", "class.json"), "{}"); - File.WriteAllText(Utils.GetFilePath("audio", "music", "track.mp3"), "music"); - File.WriteAllText(Utils.GetFilePath("audio", "voice", "cache.mp3"), "voice-cache"); - File.WriteAllText(Utils.GetFilePath("logs", "app.log"), "log"); - - var archive = provider.GetRequiredService(); - var destination = Path.Combine(_exportDirectory, "cloud.zip"); - await archive.ExportCloudBackupAsync(destination, TestContext.Current.CancellationToken); - - var paths = ReadManifestPaths(destination); - Assert.Equal(ArchiveKind.CloudBackup, ReadManifestKind(destination)); - Assert.Contains("config/settings.json", paths); - Assert.Contains("list/roll_call_list/class.json", paths); - Assert.Contains(paths, path => path.StartsWith("history/roll_call_history/", StringComparison.Ordinal)); - Assert.Contains("audio/music/track.mp3", paths); - Assert.DoesNotContain("config/device-uuid.json", paths); - Assert.DoesNotContain("audio/voice/cache.mp3", paths); - Assert.DoesNotContain("logs/app.log", paths); - Assert.DoesNotContain(paths, path => path.StartsWith("plugins", StringComparison.OrdinalIgnoreCase)); - - StampProducerVersion(destination, TestV3ProducerVersion); - var inspection = await archive.InspectCloudBackupAsync(destination, TestContext.Current.CancellationToken); - Assert.True(inspection.IsSupportedV3); - Assert.Equal(ArchiveKind.CloudBackup, inspection.Kind); - } - - [Fact] - public async Task ExportCloudBackup_FollowsTheCloudContentSelection() - { - using var provider = CreateProvider(); - var config = provider.GetRequiredService(); - // The cloud selection is independent: keep settings only, and a checked log option still - // never reaches the cloud. - config.Data.General.Backup.CloudIncludeConfig = true; - config.Data.General.Backup.CloudIncludeList = false; - config.Data.General.Backup.CloudIncludeHistory = false; - config.Data.General.Backup.CloudIncludeAudio = false; - config.Data.General.Backup.CloudIncludeCses = false; - config.Data.General.Backup.CloudIncludeImages = false; - config.Data.General.Backup.IncludeLogs = true; - config.Save(); - File.WriteAllText(Utils.GetFilePath("list", "roll_call_list", "class.json"), "{}"); - File.WriteAllText(Utils.GetFilePath("proofs", "draw.srproof.json"), "{}"); - File.WriteAllText(Utils.GetFilePath("theme", "theme.json"), "{}"); - File.WriteAllText(Utils.GetFilePath("logs", "app.log"), "log"); - - var archive = provider.GetRequiredService(); - var destination = Path.Combine(_exportDirectory, "cloud-selection.zip"); - await archive.ExportCloudBackupAsync(destination, TestContext.Current.CancellationToken); - - var paths = ReadManifestPaths(destination); - Assert.Contains("config/settings.json", paths); - Assert.DoesNotContain("list/roll_call_list/class.json", paths); - Assert.DoesNotContain("proofs/draw.srproof.json", paths); - Assert.DoesNotContain("theme/theme.json", paths); - Assert.DoesNotContain("logs/app.log", paths); - - var roots = archive.GetCloudBackupRoots(); - Assert.Contains("config/settings.json", roots); - Assert.DoesNotContain("list", roots); - Assert.DoesNotContain("proofs", roots); - Assert.DoesNotContain("themes", roots); - Assert.DoesNotContain("logs", roots); - Assert.DoesNotContain("config/device-uuid.json", roots); - } - - [Fact] - public async Task CloudBackupCarriesProofsOnlyWhenTheSelectionAsksForThem() - { - using var provider = CreateProvider(); - var config = provider.GetRequiredService(); - config.Data.General.Backup.CloudIncludeConfig = false; - config.Data.General.Backup.CloudIncludeList = false; - config.Data.General.Backup.CloudIncludeHistory = false; - config.Data.General.Backup.CloudIncludeCses = false; - config.Data.General.Backup.CloudIncludeProofs = true; - config.Save(); - File.WriteAllText(Utils.GetFilePath("proofs", "draw.srproof.json"), "{}"); - - var archive = provider.GetRequiredService(); - Assert.Contains("proofs", archive.GetCloudBackupRoots()); - - var destination = Path.Combine(_exportDirectory, "cloud-proofs.zip"); - await archive.ExportCloudBackupAsync(destination, TestContext.Current.CancellationToken); - - Assert.Contains("proofs/draw.srproof.json", ReadManifestPaths(destination)); - } - - [Fact] - public async Task InspectCloudBackup_RejectsArchivesOfOtherKinds() + public async Task ImportArchive_RejectsLegacyCloudBackupArchives() { using var provider = CreateProvider(); provider.GetRequiredService().Save(); var archive = provider.GetRequiredService(); - var destination = Path.Combine(_exportDirectory, "all-data.zip"); + var destination = Path.Combine(_exportDirectory, "legacy-cloud-backup.zip"); await archive.ExportAllDataAsync(destination, TestContext.Current.CancellationToken); StampProducerVersion(destination, TestV3ProducerVersion); - - var inspection = await archive.InspectCloudBackupAsync(destination, TestContext.Current.CancellationToken); - - Assert.False(inspection.IsSupportedV3); - Assert.Contains(inspection.Warnings, warning => warning.Contains("云端备份")); + StampManifestKind(destination, ArchiveKind.CloudBackup); var exception = await Assert.ThrowsAsync( - () => archive.ImportCloudBackupAsync(destination, TestContext.Current.CancellationToken)); - Assert.Contains("云端备份", exception.Message); - } - - [Fact] - public async Task ImportCloudBackup_RestoresDataAndKeepsDeviceIdentity() - { - var hooks = new RecordingHooks(); - using var provider = CreateProvider(hooks); - var config = provider.GetRequiredService(); - var exportedInterval = config.Data.General.Backup.AutoBackupIntervalDays; - config.Save(); - var listPath = Utils.GetFilePath("list", "roll_call_list", "class.json"); - File.WriteAllText(listPath, "{}"); - - var archive = provider.GetRequiredService(); - var destination = Path.Combine(_exportDirectory, "cloud-restore.zip"); - await archive.ExportCloudBackupAsync(destination, TestContext.Current.CancellationToken); - StampProducerVersion(destination, TestV3ProducerVersion); - var exportedListContent = File.ReadAllText(listPath); - - var identity = Utils.GetFilePath("config", "device-uuid.json"); - File.WriteAllText(identity, "{\"device_uuid\":\"local-device\"}"); - File.WriteAllText(listPath, "{\"changed\":true}"); - config.Data.General.Backup.AutoBackupIntervalDays = exportedInterval + 3; - config.Save(); - - var result = await archive.ImportCloudBackupAsync(destination, TestContext.Current.CancellationToken); - - Assert.Equal(exportedListContent, File.ReadAllText(listPath)); - Assert.Equal(exportedInterval, config.Data.General.Backup.AutoBackupIntervalDays); - Assert.Equal("{\"device_uuid\":\"local-device\"}", File.ReadAllText(identity)); - Assert.True(result.ImportedFiles > 0); - Assert.Contains("pre_import_all_data", Path.GetFileName(result.SnapshotPath)); - Assert.Equal(1, hooks.AllDataCalls); - } - - [Fact] - public async Task ImportCloudBackup_NeverCommitsACraftedDeviceIdentityEntry() - { - using var provider = CreateProvider(); - provider.GetRequiredService().Save(); - var archive = provider.GetRequiredService(); - var destination = Path.Combine(_exportDirectory, "cloud-identity.zip"); - await archive.ExportCloudBackupAsync(destination, TestContext.Current.CancellationToken); - StampProducerVersion(destination, TestV3ProducerVersion); - - var identity = Utils.GetFilePath("config", "device-uuid.json"); - File.WriteAllText(identity, "{\"device_uuid\":\"local-device\"}"); - AddArchiveEntry(destination, "config/device-uuid.json", Encoding.UTF8.GetBytes("{\"device_uuid\":\"other-device\"}")); - - var inspection = await archive.InspectCloudBackupAsync(destination, TestContext.Current.CancellationToken); - Assert.Contains("config/device-uuid.json", inspection.Roots); - - await archive.ImportCloudBackupAsync(destination, TestContext.Current.CancellationToken); + () => archive.ImportAllDataAsync(destination, TestContext.Current.CancellationToken)); - Assert.Equal("{\"device_uuid\":\"local-device\"}", File.ReadAllText(identity)); + Assert.Contains("云端备份已停止支持", exception.Message); } - public void Dispose() { ResetDataRootForTests(); @@ -886,6 +720,18 @@ private static void StampProducerVersion(string path, string producerVersion) File.WriteAllText(path, envelope.ToJsonString()); } + private static void StampManifestKind(string path, ArchiveKind kind) + { + RewriteArchive(path, (name, bytes) => + { + if (name != "manifest.json") + return bytes; + var node = JsonNode.Parse(Encoding.UTF8.GetString(bytes).TrimStart(''))!; + node["kind"] = kind.ToString(); + return Encoding.UTF8.GetBytes(node.ToJsonString()); + }); + } + private static string ReadEntryText(ZipArchiveEntry entry) { using var reader = new StreamReader(entry.Open(), Encoding.UTF8, detectEncodingFromByteOrderMarks: true); diff --git a/SecRandom.Core.Tests/DrawProofAttestationQueueTests.cs b/SecRandom.Core.Tests/DrawProofAttestationQueueTests.cs index 9d115ebc3..0b483d8ed 100644 --- a/SecRandom.Core.Tests/DrawProofAttestationQueueTests.cs +++ b/SecRandom.Core.Tests/DrawProofAttestationQueueTests.cs @@ -85,7 +85,7 @@ public async Task FailedSubmissionIsRetriedAndStoresTheReceiptOnSuccess() Assert.Equal(1, failed.PendingCount); Assert.Equal(0, failed.FailedCount); - witness.Handler = _ => Task.FromResult(new WitnessAttestationResult("receipt-token", null)); + witness.Handler = _ => Task.FromResult(new WitnessAttestationResult("receipt-token")); var succeeded = await service.RetryNowAsync(TestContext.Current.CancellationToken); Assert.Equal(0, succeeded.PendingCount); @@ -160,33 +160,6 @@ public void ProofsThatAreNotOfflineReproducibleOrAlreadyAttestedAreNotQueued() Assert.Equal(0, status.ConflictCount); } - [Fact] - public async Task AServiceChainAnchorAlertIsCountedWithoutFailingTheSubmission() - { - using var provider = CreateProvider(); - var exporter = provider.GetRequiredService(); - var witness = new RecordingWitnessClient - { - Handler = _ => Task.FromResult(new WitnessAttestationResult( - "receipt-token", - new WitnessChainAnchor { Status = "behind", HeadIndex = 5, Breaks = 1 })) - }; - var service = CreateService(provider, witness); - - var proof = CreateProof(Guid.NewGuid()); - var path = PathFor("draw-chain.srproof.json"); - exporter.SaveAtPath(path, proof); - service.Request(proof, path); - - var status = await service.RetryNowAsync(TestContext.Current.CancellationToken); - - Assert.Equal(1, status.ChainAlertCount); - Assert.Equal(0, status.PendingCount); - Assert.True(status.HasIssues); - Assert.True(exporter.TryRead(path, out var attested)); - Assert.Equal("receipt-token", attested!.Witness?.Receipt); - } - [Fact] public async Task TimestampFailureIsReportedSeparatelyFromReceiptFailure() { @@ -218,7 +191,6 @@ private static ServiceProvider CreateProvider() var services = new ServiceCollection(); services.AddLogging(builder => builder.SetMinimumLevel(LogLevel.None)); services.AddCoreRuntimeServices(); - services.AddSingleton(); services.AddSingleton(); return services.BuildServiceProvider(); } @@ -272,7 +244,7 @@ private static MethodInfo GetUtilsMethod(string name) private sealed class RecordingWitnessClient : IWitnessClient { public Func> Handler { get; set; } = - _ => Task.FromResult(new WitnessAttestationResult("receipt-token", null)); + _ => Task.FromResult(new WitnessAttestationResult("receipt-token")); public List Submitted { get; } = []; diff --git a/SecRandom.Core.Tests/PluginDrawServiceTests.cs b/SecRandom.Core.Tests/PluginDrawServiceTests.cs index 8031692e6..2ad16b53b 100644 --- a/SecRandom.Core.Tests/PluginDrawServiceTests.cs +++ b/SecRandom.Core.Tests/PluginDrawServiceTests.cs @@ -3,13 +3,13 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using SecRandom.Core.Abstraction.Services; -using SecRandom.Core.Enums; +using SecRandom.Core.Enums; using SecRandom.Core.Enums.Configs; using SecRandom.Core.Models.SubConfigs; using SecRandom.Core.Services; using SecRandom.Core.Services.Config; -using SecRandom.Core.Services.ControlNode; -using SecRandom.Core.Services.HistoryStore; +using SecRandom.Core.Services.ControlNode; +using SecRandom.Core.Services.HistoryStore; using SecRandom.Core.Services.Verification; using SecRandom.Services; using SecRandom.Services.Draw; @@ -75,11 +75,11 @@ public async Task DrawStudents_Authorized_DrawsThroughSharedPipeline() Assert.False(string.IsNullOrWhiteSpace(result.DrawRoundId)); var temporary = provider.GetRequiredService(); - Assert.Equal(1, temporary.GetStudentCounts("default", null, null)[student.RecordId.ToString("D")]); + Assert.Equal(1, temporary.GetStudentCounts("default", null, null)[student.RecordId.ToString("D")]); } [Fact] - public async Task DrawStudents_WhenCommitFails_DoesNotPublishProofOrAdvanceChain() + public async Task DrawStudents_WhenCommitFails_DoesNotPublishProof() { using var provider = CreateProvider(allowAuthorization: true); var config = provider.GetRequiredService(); @@ -91,20 +91,16 @@ public async Task DrawStudents_WhenCommitFails_DoesNotPublishProofOrAdvanceChain profile.CurrentStudentList!.Students.Add(student); profile.SaveProfile(); - var historyPath = ProfileHistoryPaths.DatabasePath(profile.CurrentStudentHistory!.Name, HistoryGroupKind.RollCall); + var historyPath = ProfileHistoryPaths.DatabasePath(profile.CurrentStudentHistory!.Name, HistoryGroupKind.RollCall); File.Delete(historyPath); Directory.CreateDirectory(historyPath); - var chain = provider.GetRequiredService(); - Assert.Equal(0, chain.Read().HeadIndex); - var service = provider.GetRequiredService(); await Assert.ThrowsAnyAsync(() => service.DrawAsync( new RollCallDrawRequest("default", string.Empty, string.Empty, 1, string.Empty), TestContext.Current.CancellationToken)); Assert.Empty(provider.GetRequiredService().EnumerateProofPaths()); - Assert.Equal(0, chain.Read().HeadIndex); Assert.Equal(0, provider.GetRequiredService().GetStatus().PendingCount); } @@ -125,12 +121,10 @@ public async Task DrawLottery_WhenCommitFails_DoesNotPublishEitherProof() profile.CurrentStudentList!.Students.Add(student); profile.SaveProfile(); - var historyPath = ProfileHistoryPaths.DatabasePath(profile.CurrentPrizeHistory!.Name, HistoryGroupKind.Lottery); + var historyPath = ProfileHistoryPaths.DatabasePath(profile.CurrentPrizeHistory!.Name, HistoryGroupKind.Lottery); File.Delete(historyPath); Directory.CreateDirectory(historyPath); - var chain = provider.GetRequiredService(); - Assert.Equal(0, chain.Read().HeadIndex); var service = provider.GetRequiredService(); await Assert.ThrowsAnyAsync(() => service.DrawAsync( @@ -138,7 +132,6 @@ await Assert.ThrowsAnyAsync(() => service.DrawAsync( TestContext.Current.CancellationToken)); Assert.Empty(provider.GetRequiredService().EnumerateProofPaths()); - Assert.Equal(0, chain.Read().HeadIndex); Assert.Equal(0, provider.GetRequiredService().GetStatus().PendingCount); } @@ -184,7 +177,6 @@ private static ServiceProvider CreateProvider(bool allowAuthorization) services.AddSingleton(); services.AddSingleton(_ => new StubWitnessClient()); services.AddSingleton(_ => new StubTimestampAuthorityClient()); - services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); @@ -227,7 +219,7 @@ private sealed class StubWitnessClient : IWitnessClient { public Task AttestAsync(DrawProof proof, CancellationToken cancellationToken) { - return Task.FromResult(new WitnessAttestationResult("attested", null)); + return Task.FromResult(new WitnessAttestationResult("attested")); } public Task NotarizeAsync(FormalNotarizationRequest request, CancellationToken cancellationToken) diff --git a/SecRandom.Core.Tests/ProofChainTests.cs b/SecRandom.Core.Tests/ProofChainTests.cs deleted file mode 100644 index c97fb9c1e..000000000 --- a/SecRandom.Core.Tests/ProofChainTests.cs +++ /dev/null @@ -1,253 +0,0 @@ -using System.Reflection; -using System.Security.Cryptography; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; -using SecRandom.Core.Services; -using SecRandom.Core.Services.Config; -using SecRandom.Services.Verification; -using SecRandom.Shared; -using SecRandom.Shared.Models.Verification; - -namespace SecRandom.Core.Tests; - -public sealed class ProofChainTests : IDisposable -{ - private readonly string _dataRoot = Path.Combine( - Path.GetTempPath(), - "SecRandom", - "proof-chain-tests", - Guid.NewGuid().ToString("N")); - - public ProofChainTests() - { - ResetDataRootForTests(); - ConfigureDataRootForTests(_dataRoot); - } - - public void Dispose() - { - ResetDataRootForTests(); - if (Directory.Exists(_dataRoot)) - Directory.Delete(_dataRoot, recursive: true); - } - - [Fact] - public void SavedProofsFormAContinuousChain() - { - using var provider = CreateProvider(); - var exporter = provider.GetRequiredService(); - var chainStore = provider.GetRequiredService(); - - var first = exporter.Save(CreateProof(new DateTimeOffset(2026, 9, 30, 1, 0, 0, TimeSpan.Zero)), Context()); - var second = exporter.Save(CreateProof(new DateTimeOffset(2026, 9, 30, 1, 5, 0, TimeSpan.Zero)), Context()); - - Assert.Equal(1, first.Proof.Chain!.Index); - Assert.Equal(2, second.Proof.Chain!.Index); - Assert.Equal(first.Proof.Chain.SelfHash, second.Proof.Chain.PrevHash); - - var head = chainStore.Read(); - Assert.Equal(2, head.HeadIndex); - Assert.Equal(second.Proof.Chain.SelfHash, head.HeadHash); - } - - [Fact] - public void VerifierAcceptsAnIntactChainAndCountsLegacyProofs() - { - using var provider = CreateProvider(); - var exporter = provider.GetRequiredService(); - var verifier = provider.GetRequiredService(); - - exporter.Save(CreateProof(new DateTimeOffset(2026, 9, 30, 1, 0, 0, TimeSpan.Zero)), Context()); - exporter.Save(CreateProof(new DateTimeOffset(2026, 9, 30, 1, 5, 0, TimeSpan.Zero)), Context()); - exporter.SaveAtPath(PathFor("legacy.srproof.json"), CreateProof(new DateTimeOffset(2026, 9, 30, 1, 10, 0, TimeSpan.Zero))); - - var report = verifier.Verify(TestContext.Current.CancellationToken); - - Assert.True(report.IsHealthy); - Assert.Equal(2, report.Chained); - Assert.Equal(1, report.Unchained); - Assert.Equal(3, report.Total); - } - - [Fact] - public void VerifierReportsAMissingProofInTheMiddleOfTheChain() - { - using var provider = CreateProvider(); - var exporter = provider.GetRequiredService(); - var verifier = provider.GetRequiredService(); - - var first = exporter.Save(CreateProof(new DateTimeOffset(2026, 9, 30, 1, 0, 0, TimeSpan.Zero)), Context()); - exporter.Save(CreateProof(new DateTimeOffset(2026, 9, 30, 1, 5, 0, TimeSpan.Zero)), Context()); - exporter.Save(CreateProof(new DateTimeOffset(2026, 9, 30, 1, 10, 0, TimeSpan.Zero)), Context()); - File.Delete(first.Path); - - var report = verifier.Verify(TestContext.Current.CancellationToken); - - Assert.False(report.IsHealthy); - Assert.Equal(1, report.Gaps); - Assert.Contains(report.Issues, issue => issue.Kind == ProofIntegrityIssueKind.Gap); - } - - [Fact] - public void VerifierReportsAProofWhoseContentWasRewritten() - { - using var provider = CreateProvider(); - var exporter = provider.GetRequiredService(); - var verifier = provider.GetRequiredService(); - - var saved = exporter.Save(CreateProof(new DateTimeOffset(2026, 9, 30, 1, 0, 0, TimeSpan.Zero)), Context()); - exporter.SaveAtPath(saved.Path, saved.Proof with { Payload = "rewritten-payload" }); - - var report = verifier.Verify(TestContext.Current.CancellationToken); - - Assert.False(report.IsHealthy); - Assert.Equal(1, report.Modified); - Assert.Contains(report.Issues, issue => issue.Kind == ProofIntegrityIssueKind.Modified); - } - - [Fact] - public void RetentionCleanupIsRecordedSoExpiredProofsAreNotReportedAsGaps() - { - using var provider = CreateProvider(); - var exporter = provider.GetRequiredService(); - var chainStore = provider.GetRequiredService(); - var verifier = provider.GetRequiredService(); - var config = provider.GetRequiredService(); - - var first = exporter.Save(CreateProof(new DateTimeOffset(2026, 9, 30, 1, 0, 0, TimeSpan.Zero)), Context()); - var second = exporter.Save(CreateProof(new DateTimeOffset(2026, 9, 30, 1, 5, 0, TimeSpan.Zero)), Context()); - - var expired = DateTime.UtcNow.AddDays(-10); - File.SetLastWriteTimeUtc(first.Path, expired); - File.SetLastWriteTimeUtc(second.Path, expired); - config.Data.General.ProofRetention.RetentionDays = 1; - - exporter.Save(CreateProof(new DateTimeOffset(2026, 9, 30, 1, 10, 0, TimeSpan.Zero)), Context()); - - Assert.False(File.Exists(first.Path)); - Assert.False(File.Exists(second.Path)); - Assert.Equal(2, chainStore.Read().RetainedFromIndex); - - var report = verifier.Verify(TestContext.Current.CancellationToken); - Assert.True(report.IsHealthy); - Assert.Equal(0, report.Gaps); - } - - [Fact] - public void TimestampValidationRejectsAnythingThatIsNotAUsableToken() - { - var hash = SHA256.HashData("proof-digest"u8); - - Assert.False(TimestampAuthorityClient.Validate("not-base64!", hash).IsValid); - Assert.False(TimestampAuthorityClient.Validate(Convert.ToBase64String("plain-text"u8), hash).IsValid); - Assert.False(TimestampAuthorityClient.Validate(string.Empty, hash).IsValid); - } - - [Fact] - public void RecordedRemovalsOnlyAdvanceTheFloorOverAContiguousPrefix() - { - using var provider = CreateProvider(); - var chainStore = provider.GetRequiredService(); - - chainStore.RecordRemovedIndices([10], ProofChainEvent.StorageLimitCleanup); - Assert.Equal(0, chainStore.Read().RetainedFromIndex); - - chainStore.RecordRemovedIndices([1], ProofChainEvent.StorageLimitCleanup); - Assert.Equal(1, chainStore.Read().RetainedFromIndex); - - chainStore.RecordRemovedIndices([2], ProofChainEvent.RetentionCleanup); - // Index 10 is recorded but still not contiguous, so the floor stops at 2 instead of jumping to 10. - Assert.Equal(2, chainStore.Read().RetainedFromIndex); - } - - [Fact] - public void SparseCleanupCannotHideAnUnrecordedDeletion() - { - using var provider = CreateProvider(); - var exporter = provider.GetRequiredService(); - var chainStore = provider.GetRequiredService(); - var verifier = provider.GetRequiredService(); - - var first = exporter.Save(CreateProof(new DateTimeOffset(2026, 9, 30, 1, 0, 0, TimeSpan.Zero)), Context()); - exporter.Save(CreateProof(new DateTimeOffset(2026, 9, 30, 1, 5, 0, TimeSpan.Zero)), Context()); - var third = exporter.Save(CreateProof(new DateTimeOffset(2026, 9, 30, 1, 10, 0, TimeSpan.Zero)), Context()); - - // The oldest proof disappears without being recorded, while an unrelated cleanup claims only the - // newest index. That must not reclassify the surviving hole as retention-expired. - File.Delete(first.Path); - chainStore.RecordRemovedIndices([third.Proof.Chain!.Index], ProofChainEvent.StorageLimitCleanup); - - Assert.Equal(0, chainStore.Read().RetainedFromIndex); - var report = verifier.Verify(TestContext.Current.CancellationToken); - Assert.False(report.IsHealthy); - Assert.Contains(report.Issues, issue => issue.Kind == ProofIntegrityIssueKind.Gap); - } - - [Fact] - public void StorageLimitCleanupKeepsTheProofItJustSaved() - { - using var provider = CreateProvider(); - var exporter = provider.GetRequiredService(); - var verifier = provider.GetRequiredService(); - var config = provider.GetRequiredService(); - - config.Data.General.ProofRetention.RetentionDays = 0; - // Far below the size of a single proof: the proof written by this save must still survive, otherwise - // the chain head would point at a file that never landed and the attestation queue at a dead path. - config.Data.General.ProofRetention.MaximumStorageBytes = 1; - - var saved = exporter.Save(CreateProof(new DateTimeOffset(2026, 9, 30, 1, 0, 0, TimeSpan.Zero)), Context()); - - Assert.True(File.Exists(saved.Path)); - var report = verifier.Verify(TestContext.Current.CancellationToken); - Assert.Equal(1, report.Chained); - Assert.Equal(0, report.MissingTail); - } - - private static ServiceProvider CreateProvider() - { - var services = new ServiceCollection(); - services.AddLogging(builder => builder.SetMinimumLevel(LogLevel.None)); - services.AddCoreRuntimeServices(); - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - return services.BuildServiceProvider(); - } - - private static DrawProofExportContext Context() => DrawProofExportContext.ForStudents("默认名单"); - - private static string PathFor(string fileName) => Utils.GetFilePath("proofs", fileName); - - private static DrawProof CreateProof(DateTimeOffset createdAt) - { - return new DrawProof - { - ProofId = Guid.NewGuid(), - Mode = VerificationProofMode.OfflineReproducible, - CreatedAtUtc = createdAt, - AlgorithmId = "secrandom-student-fair-repeat/v3", - AlgorithmEngineVersion = "3.3.0", - InputHash = "input-hash", - Payload = "payload", - AuditPayload = "audit-payload", - Result = new DrawProofResult { WinnerRecordIds = [Guid.NewGuid()] } - }; - } - - private static void ConfigureDataRootForTests(string dataRoot) - { - GetUtilsMethod("ConfigureDataRoot").Invoke(null, [dataRoot]); - } - - private static void ResetDataRootForTests() - { - GetUtilsMethod("ResetDataRootForTests").Invoke(null, null); - } - - private static MethodInfo GetUtilsMethod(string name) - { - return typeof(Utils).GetMethod(name, BindingFlags.Static | BindingFlags.NonPublic) - ?? throw new InvalidOperationException($"Utils.{name} was not found."); - } -} diff --git a/SecRandom.Core.Tests/SectlCloudStorageClientTests.cs b/SecRandom.Core.Tests/SectlCloudStorageClientTests.cs deleted file mode 100644 index 10b3da5b1..000000000 --- a/SecRandom.Core.Tests/SectlCloudStorageClientTests.cs +++ /dev/null @@ -1,276 +0,0 @@ -using System.Net; -using System.Text; -using System.Text.Json; -using System.Text.Json.Nodes; -using Microsoft.Extensions.Logging.Abstractions; -using SecRandom.Core.Abstraction; -using SecRandom.Core.Models; -using SecRandom.Core.Services.Config; -using SecRandom.Services.Auth; -using SecRandom.Services.Config; - -namespace SecRandom.Core.Tests; - -public sealed class SectlCloudStorageClientTests -{ - private const string ClientId = SectlAuthService.ClientId; - - [Fact] - public async Task ListFilesAsync_PagesUntilHasMoreIsFalseAndMapsFiles() - { - var requestedUris = new List(); - var client = CreateCloudClient(request => - { - requestedUris.Add(request.RequestUri!.ToString()); - return request.RequestUri.Query.Contains("offset=500") - ? Json("{\"files\":[{\"file_id\":\"f2\",\"filename\":\"SecRandom-cloud-b-p01of01.srpart\",\"size\":20}],\"has_more\":false}") - : Json("{\"files\":[{\"file_id\":\"f1\",\"file_document_id\":\"d1\",\"filename\":\"SecRandom-cloud-a-manifest.json\",\"size\":10,\"created_at\":\"2026-08-30T12:00:00Z\"}],\"has_more\":true}"); - }); - - var files = await client.ListFilesAsync(TestContext.Current.CancellationToken); - - Assert.Equal(2, files.Count); - Assert.Equal("f1", files[0].FileId); - Assert.Equal("d1", files[0].FileDocumentId); - Assert.Equal("SecRandom-cloud-a-manifest.json", files[0].FileName); - Assert.Equal(20, files[1].Size); - Assert.Null(files[1].CreatedAt); - Assert.Equal(2, requestedUris.Count); - Assert.All(requestedUris, uri => Assert.Contains($"client_id={ClientId}", uri)); - Assert.Contains("offset=500", requestedUris[1]); - } - - [Fact] - public async Task UploadAsync_SendsBase64PartWithPlatformScope() - { - HttpRequestMessage? captured = null; - string? capturedBody = null; - var client = CreateCloudClient(request => - { - captured = request; - capturedBody = request.Content!.ReadAsStringAsync().GetAwaiter().GetResult(); - return Json("{\"success\":true,\"file_id\":\"fid\",\"filename\":\"part.srpart\",\"size\":4}"); - }); - - var uploaded = await client.UploadAsync("part.srpart", "application/octet-stream", [1, 2, 3, 4], - TestContext.Current.CancellationToken); - - Assert.NotNull(captured); - Assert.Equal(HttpMethod.Post, captured!.Method); - Assert.Equal($"https://appwrite.sectl.cn/api/cloud/upload?client_id={ClientId}", captured.RequestUri!.ToString()); - Assert.Equal("Bearer access-token", captured.Headers.Authorization?.ToString()); - - var payload = JsonNode.Parse(capturedBody!)!; - Assert.Equal(ClientId, payload["client_id"]!.GetValue()); - Assert.Equal("part.srpart", payload["file"]!["name"]!.GetValue()); - Assert.Equal(4, payload["file"]!["size"]!.GetValue()); - Assert.StartsWith("data:application/octet-stream;base64,", payload["file"]!["data"]!.GetValue()); - - Assert.Equal("fid", uploaded.FileId); - Assert.Equal(4, uploaded.Size); - } - - [Fact] - public async Task UploadAsync_RejectsAPartLargerThanTheUploadLimit() - { - var requests = 0; - var client = CreateCloudClient(_ => - { - requests++; - return Json("{}"); - }); - - var exception = await Assert.ThrowsAsync(() => - client.UploadAsync("part.srpart", "application/octet-stream", new byte[5 * 1024 * 1024], - TestContext.Current.CancellationToken)); - - Assert.Equal("payload_too_large", exception.Code); - Assert.Equal(0, requests); - } - - [Fact] - public async Task DownloadAsync_ResolvesTheShortLivedUrlBeforeFetchingBytes() - { - var captured = new List(); - var bytes = new byte[] { 9, 8, 7 }; - var client = CreateCloudClient(request => - { - captured.Add(request); - return request.RequestUri!.AbsolutePath.EndsWith("/download", StringComparison.Ordinal) - ? Json("{\"download_url\":\"https://storage.example/token/abc\",\"expires_at\":\"2026-08-30T12:05:00Z\"}") - : new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent(bytes) }; - }); - - var downloaded = await client.DownloadAsync("f1", TestContext.Current.CancellationToken); - - Assert.Equal(bytes, downloaded); - Assert.Equal(2, captured.Count); - Assert.Equal("Bearer access-token", captured[0].Headers.Authorization?.ToString()); - Assert.Equal("https://storage.example/token/abc", captured[1].RequestUri!.ToString()); - Assert.Null(captured[1].Headers.Authorization); - } - - [Fact] - public async Task DeleteAsync_SendsPlatformScopedBody() - { - string? capturedBody = null; - HttpMethod? method = null; - string? uri = null; - var client = CreateCloudClient(request => - { - method = request.Method; - uri = request.RequestUri!.ToString(); - capturedBody = request.Content!.ReadAsStringAsync().GetAwaiter().GetResult(); - return Json("{\"success\":true}"); - }); - - await client.DeleteAsync("f1", "d1", TestContext.Current.CancellationToken); - - Assert.Equal(HttpMethod.Delete, method); - Assert.Equal($"https://appwrite.sectl.cn/api/cloud/files/f1?client_id={ClientId}", uri); - var payload = JsonNode.Parse(capturedBody!)!; - Assert.Equal(ClientId, payload["client_id"]!.GetValue()); - Assert.Equal("d1", payload["file_document_id"]!.GetValue()); - } - - [Fact] - public async Task GetUsageAsync_MapsQuotaFields() - { - var client = CreateCloudClient(_ => Json( - "{\"used_storage\":100,\"total_storage\":1000,\"available_storage\":900,\"percentage\":10,\"file_count\":3,\"platform_used_storage\":40,\"platform_file_count\":2}")); - - var quota = await client.GetUsageAsync(TestContext.Current.CancellationToken); - - Assert.Equal(100, quota.Used); - Assert.Equal(1000, quota.Total); - Assert.Equal(900, quota.Available); - Assert.Equal(3, quota.FileCount); - Assert.Equal(40, quota.PlatformUsed); - Assert.Equal(2, quota.PlatformFileCount); - } - - [Theory] - [InlineData(HttpStatusCode.RequestEntityTooLarge, "", "payload_too_large")] - [InlineData(HttpStatusCode.RequestEntityTooLarge, "{\"error\":\"storage_exceeded\",\"error_description\":\"Storage quota exceeded\"}", "storage_exceeded")] - [InlineData(HttpStatusCode.Forbidden, "{\"error\":\"cloud_service_disabled\",\"error_description\":\"该平台未启用云服务\"}", "cloud_service_disabled")] - [InlineData(HttpStatusCode.Forbidden, "{\"error\":\"insufficient_scope\",\"error_description\":\"Missing cloud:write permission\"}", "insufficient_scope")] - [InlineData(HttpStatusCode.Unauthorized, "{\"error\":\"invalid_token\",\"error_description\":\"The access token is invalid or has expired\"}", "invalid_token")] - [InlineData(HttpStatusCode.InternalServerError, "{\"error\":\"internal_error\",\"error_description\":\"boom\"}", "internal_error")] - [InlineData(HttpStatusCode.InternalServerError, "{}", "cloud_timeout")] - [InlineData(HttpStatusCode.InternalServerError, "not-json", "cloud_timeout")] - [InlineData(HttpStatusCode.InternalServerError, "{\"type\":\"general_unknown\",\"message\":\"boom\"}", "cloud_timeout")] - public async Task ServiceErrors_KeepTheServiceErrorCode(HttpStatusCode status, string body, string expectedCode) - { - var client = CreateCloudClient(_ => new HttpResponseMessage(status) - { - Content = new StringContent(body, Encoding.UTF8, "application/json") - }); - - var exception = await Assert.ThrowsAsync(() => - client.GetUsageAsync(TestContext.Current.CancellationToken)); - - Assert.Equal(expectedCode, exception.Code); - } - - [Fact] - public async Task GatewayTimeout_ReportsStatusAndEmptyBodyForDiagnosis() - { - var client = CreateCloudClient(_ => new HttpResponseMessage(HttpStatusCode.InternalServerError) - { - Content = new StringContent("{}", Encoding.UTF8, "application/json") - }); - - var exception = await Assert.ThrowsAsync(() => - client.GetUsageAsync(TestContext.Current.CancellationToken)); - - Assert.Equal("cloud_timeout", exception.Code); - Assert.Contains("HTTP 500", exception.Message); - Assert.Contains("空响应", exception.Message); - } - - [Fact] - public async Task CloudRequests_WhenSignedOut_FailWithASignInMessage() - { - var client = CreateCloudClient(_ => Json("{}"), signedIn: false); - - await Assert.ThrowsAsync(() => - client.ListFilesAsync(TestContext.Current.CancellationToken)); - } - - [Fact] - public async Task CloudRequests_WhenTheAccessTokenIsRejected_RefreshAndRetryOnce() - { - var tokens = new List(); - var listAttempts = 0; - var client = CreateCloudClient(request => - { - var path = request.RequestUri!.AbsolutePath; - if (path == "/api/oauth/refresh") - return Json("{\"access_token\":\"refreshed-access-token\",\"refresh_token\":\"refreshed-refresh-token\",\"user_id\":\"user-1\",\"expires_in\":3600}"); - - tokens.Add(request.Headers.Authorization?.Parameter); - listAttempts++; - return listAttempts == 1 - ? new HttpResponseMessage(HttpStatusCode.Unauthorized) - { - Content = new StringContent("{\"error\":\"invalid_token\"}", Encoding.UTF8, "application/json") - } - : Json("{\"files\":[],\"has_more\":false}"); - }); - - var files = await client.ListFilesAsync(TestContext.Current.CancellationToken); - - Assert.Empty(files); - Assert.Equal(["access-token", "refreshed-access-token"], tokens); - } - - private static SectlCloudStorageClient CreateCloudClient( - Func send, bool signedIn = true) - { - var httpClient = new HttpClient(new StubHttpMessageHandler(send)) - { - BaseAddress = new Uri("https://appwrite.sectl.cn/") - }; - var factory = new StubHttpClientFactory(httpClient); - var configHandler = new MainConfigHandler( - NullLogger.Instance, - new TestConfigService(new MainConfigModel())); - var deviceUuidStore = new DeviceUuidStore(configHandler, NullLogger.Instance); - var authService = new SectlAuthService(TestTokenStore.Create(), factory, deviceUuidStore, - NullLogger.Instance, new LoopbackAuthRedirectBrokerFactory()); - if (signedIn) - SetToken(authService, new SectlToken("access-token", "refresh-token", "user-1", 3600)); - return new SectlCloudStorageClient(authService, factory, NullLogger.Instance); - } - - private static void SetToken(SectlAuthService service, SectlToken token) - { - var field = typeof(SectlAuthService).GetField("_token", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic); - Assert.NotNull(field); - field!.SetValue(service, token); - } - - private static HttpResponseMessage Json(string body) => new(HttpStatusCode.OK) - { - Content = new StringContent(body, Encoding.UTF8, "application/json") - }; - - private sealed class StubHttpClientFactory(HttpClient client) : IHttpClientFactory - { - public HttpClient CreateClient(string name) => client; - } - - private sealed class StubHttpMessageHandler(Func send) : HttpMessageHandler - { - protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) - => Task.FromResult(send(request)); - } - - private sealed class TestConfigService(MainConfigModel config) : ConfigServiceBase - { - public override bool IsConfigExists(T fallback) => true; - public override T LoadConfig(T fallback) => config is T typed ? typed : fallback; - public override void SaveConfig(T value) { } - public override void DeleteConfig(T value) { } - } -} diff --git a/SecRandom.Core.Tests/SettingsIntegrityCommandGateTests.cs b/SecRandom.Core.Tests/SettingsIntegrityCommandGateTests.cs deleted file mode 100644 index 9ba5d3bca..000000000 --- a/SecRandom.Core.Tests/SettingsIntegrityCommandGateTests.cs +++ /dev/null @@ -1,32 +0,0 @@ -using SecRandom.Services.Security; - -namespace SecRandom.Core.Tests; - -public sealed class SettingsIntegrityCommandGateTests -{ - [Fact] - public void TryRun_WhenConfirmationIsPending_RejectsWithoutRunningCommand() - { - var ran = false; - - var allowed = SettingsIntegrityCommandGate.TryRun( - confirmationPending: true, - () => ran = true); - - Assert.False(allowed); - Assert.False(ran); - } - - [Fact] - public void TryRun_WhenConfirmationIsNotPending_RunsCommand() - { - var ran = false; - - var allowed = SettingsIntegrityCommandGate.TryRun( - confirmationPending: false, - () => ran = true); - - Assert.True(allowed); - Assert.True(ran); - } -} diff --git a/SecRandom.Core.Tests/SettingsIntegrityRecoveryServiceTests.cs b/SecRandom.Core.Tests/SettingsIntegrityRecoveryServiceTests.cs deleted file mode 100644 index 342a21240..000000000 --- a/SecRandom.Core.Tests/SettingsIntegrityRecoveryServiceTests.cs +++ /dev/null @@ -1,335 +0,0 @@ -using System.IO.Compression; -using System.Text; -using System.Text.Json; -using Microsoft.Extensions.Logging.Abstractions; -using SecRandom.Core.Abstraction; -using SecRandom.Core.Enums.Configs; -using SecRandom.Core.Models; -using SecRandom.Core.Services.Archive; -using SecRandom.Core.Services.Config; -using SecRandom.Services.ImportExport; -using SecRandom.Services.Security; - -namespace SecRandom.Core.Tests; - -public sealed class SettingsIntegrityRecoveryServiceTests : IDisposable -{ - private readonly string _temporaryRoot = Path.Combine( - Path.GetTempPath(), "SecRandom", "settings-recovery-tests", Guid.NewGuid().ToString("N")); - - [Fact] - public async Task TryRecoverAsync_RestoresTheNewestLocalBackupAndKeepsThePreviousFile() - { - var fixture = CreateFixture(SettingsIntegrityRestoreSource.Local); - var tampered = WriteCurrentSettings(fixture, SettingsIntegrityRestoreSource.CloudThenLocal); - WriteBackup(fixture, "SecRandom_auto_old.zip", CreateSettings(SettingsIntegrityRestoreSource.Local), - DateTimeOffset.UtcNow.AddDays(-2)); - var newest = WriteBackup(fixture, "SecRandom_auto_new.zip", - CreateSettings(SettingsIntegrityRestoreSource.LocalThenCloud), DateTimeOffset.UtcNow.AddDays(-1)); - - var result = await fixture.Service.TryRecoverAsync(TestContext.Current.CancellationToken); - - Assert.True(result.Succeeded); - Assert.False(result.FromCloud); - Assert.Equal(newest, result.BackupName); - Assert.NotNull(result.PreRestorePath); - Assert.Equal(tampered, File.ReadAllText(result.PreRestorePath!)); - Assert.Equal(BackupMarker(SettingsIntegrityRestoreSource.LocalThenCloud), - fixture.Handler.Data.General.Backup.AutoBackupIntervalDays); - } - - [Fact] - public async Task TryRecoverAsync_SkipsBackupsWithoutASettingsFile() - { - var fixture = CreateFixture(SettingsIntegrityRestoreSource.Local); - WriteCurrentSettings(fixture, SettingsIntegrityRestoreSource.Local); - WriteBackup(fixture, "SecRandom_manual_other.zip", null, DateTimeOffset.UtcNow); - var usable = WriteBackup(fixture, "SecRandom_auto_usable.zip", - CreateSettings(SettingsIntegrityRestoreSource.CloudThenLocal), DateTimeOffset.UtcNow.AddDays(-1)); - - var result = await fixture.Service.TryRecoverAsync(TestContext.Current.CancellationToken); - - Assert.True(result.Succeeded); - Assert.Equal(usable, result.BackupName); - Assert.Equal(BackupMarker(SettingsIntegrityRestoreSource.CloudThenLocal), - fixture.Handler.Data.General.Backup.AutoBackupIntervalDays); - } - - [Fact] - public async Task TryRecoverAsync_SkipsBackupsWhoseSettingsFileCannotBeLoaded() - { - var fixture = CreateFixture(SettingsIntegrityRestoreSource.Local); - WriteCurrentSettings(fixture, SettingsIntegrityRestoreSource.Local); - WriteRawBackup(fixture, "SecRandom_auto_broken.zip", "{ not json", DateTimeOffset.UtcNow); - var usable = WriteBackup(fixture, "SecRandom_auto_usable.zip", - CreateSettings(SettingsIntegrityRestoreSource.CloudThenLocal), DateTimeOffset.UtcNow.AddDays(-1)); - - var result = await fixture.Service.TryRecoverAsync(TestContext.Current.CancellationToken); - - Assert.True(result.Succeeded); - Assert.Equal(usable, result.BackupName); - Assert.Equal(BackupMarker(SettingsIntegrityRestoreSource.CloudThenLocal), - fixture.Handler.Data.General.Backup.AutoBackupIntervalDays); - } - - [Fact] - public async Task TryRecoverAsync_WithoutAUsableBackup_KeepsTheCurrentFileAndReportsNoBackup() - { - var fixture = CreateFixture(SettingsIntegrityRestoreSource.Local); - var tampered = WriteCurrentSettings(fixture, SettingsIntegrityRestoreSource.Local); - - var result = await fixture.Service.TryRecoverAsync(TestContext.Current.CancellationToken); - - Assert.False(result.Succeeded); - Assert.Equal(SettingsIntegrityRecoveryStatus.NoBackupAvailable, result.Status); - Assert.Equal(tampered, File.ReadAllText(fixture.ConfigPath)); - Assert.False(Directory.Exists(Path.Combine(fixture.BackupDirectory, "integrity"))); - } - - [Fact] - public async Task TryRecoverAsync_WhenCloudIsPreferredButNoAccountIsSignedIn_ReportsTheCloudReason() - { - var fixture = CreateFixture(SettingsIntegrityRestoreSource.CloudThenLocal); - WriteCurrentSettings(fixture, SettingsIntegrityRestoreSource.CloudThenLocal); - - var result = await fixture.Service.TryRecoverAsync(TestContext.Current.CancellationToken); - - Assert.False(result.Succeeded); - Assert.Equal(SettingsIntegrityRecoveryStatus.CloudNotSignedIn, result.Status); - } - - [Fact] - public async Task TryRecoverAsync_WhenLocalIsPrimary_DoesNotReportTheCloudReason() - { - var fixture = CreateFixture(SettingsIntegrityRestoreSource.LocalThenCloud); - WriteCurrentSettings(fixture, SettingsIntegrityRestoreSource.LocalThenCloud); - - var result = await fixture.Service.TryRecoverAsync(TestContext.Current.CancellationToken); - - Assert.False(result.Succeeded); - Assert.Equal(SettingsIntegrityRecoveryStatus.NoBackupAvailable, result.Status); - } - - [Fact] - public void OrderCloudCandidates_UsesOnlyThisDevicesBackupsEvenWhenAnotherDeviceHasANewerOne() - { - var own = CloudBackup("own", "dev-a", DateTimeOffset.UtcNow.AddDays(-5)); - var other = CloudBackup("other", "dev-b", DateTimeOffset.UtcNow); - - var ordered = SettingsIntegrityRecoveryService.OrderCloudCandidates([other, own], "dev-a"); - - // Another machine's settings.json describes that machine, so it is never a restore candidate. - Assert.Equal(["own"], ordered.Select(item => item.BackupId)); - } - - [Fact] - public void OrderCloudCandidates_OrdersThisDevicesBackupsNewestFirst() - { - var ownOlder = CloudBackup("own-old", "dev-a", DateTimeOffset.UtcNow.AddDays(-3)); - var ownNewer = CloudBackup("own-new", "dev-a", DateTimeOffset.UtcNow.AddDays(-1)); - var other = CloudBackup("other", "dev-b", DateTimeOffset.UtcNow); - - var ordered = SettingsIntegrityRecoveryService.OrderCloudCandidates([ownOlder, other, ownNewer], "dev-a"); - - Assert.Equal(["own-new", "own-old"], ordered.Select(item => item.BackupId)); - } - - [Fact] - public void OrderCloudCandidates_WithoutThisDevicesBackups_ReturnsNothing() - { - var older = CloudBackup("other-old", "dev-b", DateTimeOffset.UtcNow.AddDays(-2)); - var newer = CloudBackup("other-new", "dev-c", DateTimeOffset.UtcNow); - - var ordered = SettingsIntegrityRecoveryService.OrderCloudCandidates([older, newer], "dev-a"); - - // No own backup means no recovery from the cloud at all: the local file stays untouched. - Assert.Empty(ordered); - } - - [Fact] - public void OrderCloudCandidates_SkipsIncompleteBackups() - { - var incomplete = CloudBackup("half", "dev-a", DateTimeOffset.UtcNow, complete: false); - var usable = CloudBackup("usable", "dev-a", DateTimeOffset.UtcNow.AddDays(-1)); - - var ordered = SettingsIntegrityRecoveryService.OrderCloudCandidates([incomplete, usable], "dev-a"); - - Assert.Equal(["usable"], ordered.Select(item => item.BackupId)); - } - - [Fact] - public void OrderCloudCandidates_WithoutADeviceTag_ReturnsNothing() - { - // A host name that yields no ASCII-safe alias means no backup can be attributed to this device. - var older = CloudBackup("older", "dev-a", DateTimeOffset.UtcNow.AddDays(-1)); - var newer = CloudBackup("newer", "dev-b", DateTimeOffset.UtcNow); - - var ordered = SettingsIntegrityRecoveryService.OrderCloudCandidates([older, newer], string.Empty); - - Assert.Empty(ordered); - } - - private static CloudBackupDescriptor CloudBackup(string backupId, string deviceTag, DateTimeOffset createdAt, - bool complete = true) => - new(backupId, $"{backupId} ({deviceTag})", createdAt, 10, 1, complete, - complete ? $"manifest-{backupId}" : null, deviceTag); - - public void Dispose() - { - if (Directory.Exists(_temporaryRoot)) - Directory.Delete(_temporaryRoot, recursive: true); - } - - private RecoveryFixture CreateFixture(SettingsIntegrityRestoreSource source) - { - var directory = Path.Combine(_temporaryRoot, Guid.NewGuid().ToString("N")); - var configPath = Path.Combine(directory, "config", "settings.json"); - var backupDirectory = Path.Combine(directory, "backup"); - Directory.CreateDirectory(Path.GetDirectoryName(configPath)!); - Directory.CreateDirectory(backupDirectory); - - var handler = new MainConfigHandler( - NullLogger.Instance, - new JsonFileConfigService(configPath)); - // 安全设置住在自己的加密文件里,settings.json 的恢复不再碰它 - var securitySettings = new SecuritySettingsStore( - Path.Combine(directory, "security", "settings.json"), - handler, - credentialStore: null, - NullLogger.Instance); - securitySettings.Data.SettingsIntegrityRestoreSource = source; - var service = new SettingsIntegrityRecoveryService( - handler, - securitySettings, - new StubImportExportService(), - NullLogger.Instance, - configPath, - backupDirectory); - return new RecoveryFixture(handler, securitySettings, service, configPath, backupDirectory); - } - - private static string WriteCurrentSettings(RecoveryFixture fixture, SettingsIntegrityRestoreSource source) - { - var content = JsonSerializer.Serialize(CreateSettings(source), ConfigServiceBase.JsonOptions); - File.WriteAllText(fixture.ConfigPath, content); - return content; - } - - private static string WriteBackup(RecoveryFixture fixture, string fileName, MainConfigModel? settings, - DateTimeOffset createdAt) - { - using var archive = ZipFile.Open(Path.Combine(fixture.BackupDirectory, fileName), ZipArchiveMode.Create); - if (settings is not null) - { - using var stream = archive.CreateEntry(SettingsIntegrityRecoveryService.SettingsEntryPath).Open(); - stream.Write(Encoding.UTF8.GetBytes(JsonSerializer.Serialize(settings, ConfigServiceBase.JsonOptions))); - } - - return Stamp(fixture, fileName, createdAt); - } - - private static string WriteRawBackup(RecoveryFixture fixture, string fileName, string settingsJson, - DateTimeOffset createdAt) - { - using var archive = ZipFile.Open(Path.Combine(fixture.BackupDirectory, fileName), ZipArchiveMode.Create); - using (var stream = archive.CreateEntry(SettingsIntegrityRecoveryService.SettingsEntryPath).Open()) - stream.Write(Encoding.UTF8.GetBytes(settingsJson)); - - return Stamp(fixture, fileName, createdAt); - } - - private static string Stamp(RecoveryFixture fixture, string fileName, DateTimeOffset createdAt) - { - var path = Path.Combine(fixture.BackupDirectory, fileName); - File.SetCreationTimeUtc(path, createdAt.UtcDateTime); - File.SetLastWriteTimeUtc(path, createdAt.UtcDateTime); - return fileName; - } - - private static MainConfigModel CreateSettings(SettingsIntegrityRestoreSource source) - { - var settings = new MainConfigModel(); - // 安全设置已经不随备份走,所以这里用一个普通的设置值当"这是哪一份备份"的标记 - settings.General.Backup.AutoBackupIntervalDays = BackupMarker(source); - return settings; - } - - /// 每份备份写一个不同的标记值,恢复后必须等于所选用备份里的那个值。 - private static int BackupMarker(SettingsIntegrityRestoreSource source) => (int)source + 1; - - private sealed record RecoveryFixture( - MainConfigHandler Handler, - SecuritySettingsStore SecuritySettings, - SettingsIntegrityRecoveryService Service, - string ConfigPath, - string BackupDirectory); - - private sealed class JsonFileConfigService(string path) : ConfigServiceBase - { - public override bool IsConfigExists(T fallback) => File.Exists(path); - - public override T LoadConfig(T fallback) => - File.Exists(path) - ? JsonSerializer.Deserialize(File.ReadAllText(path), JsonOptions) ?? fallback - : fallback; - - public override void SaveConfig(T config) => - File.WriteAllText(path, JsonSerializer.Serialize(config, JsonOptions)); - - public override void DeleteConfig(T config) - { - if (File.Exists(path)) - File.Delete(path); - } - } - - /// - /// 归档校验在恢复流程里只决定「这个候选能不能用」;单元测试关注设置文件的读取与覆盖, - /// 因此这里固定返回受支持的 v3 归档,真实的归档校验由 Core 归档测试覆盖。 - /// - private sealed class StubImportExportService : IImportExportService - { - public Task InspectAllDataAsync(string sourcePath, CancellationToken cancellationToken = default) => - Task.FromResult(Supported()); - - public Task InspectCloudBackupAsync(string sourcePath, CancellationToken cancellationToken = default) => - Task.FromResult(Supported()); - - public Task ExportDiagnosticAsync(string destinationPath, bool includeExtendedData = false, - CancellationToken cancellationToken = default) => throw new NotSupportedException(); - - public Task ExportSettingsAsync(string destinationPath, CancellationToken cancellationToken = default) => - throw new NotSupportedException(); - - public Task ExportAllDataAsync(string destinationPath, CancellationToken cancellationToken = default) => - throw new NotSupportedException(); - - public Task ExportCloudBackupAsync(string destinationPath, CancellationToken cancellationToken = default) => - throw new NotSupportedException(); - - public IReadOnlyList GetCloudBackupRoots() => []; - - public Task InspectSettingsAsync(string sourcePath, CancellationToken cancellationToken = default) => - throw new NotSupportedException(); - - public Task ImportSettingsAsync(string sourcePath, CancellationToken cancellationToken = default) => - throw new NotSupportedException(); - - public Task ImportAllDataAsync(string sourcePath, CancellationToken cancellationToken = default) => - throw new NotSupportedException(); - - public Task ImportCloudBackupAsync(string sourcePath, CancellationToken cancellationToken = default) => - throw new NotSupportedException(); - - public string CreateManualBackup(IReadOnlyCollection roots) => throw new NotSupportedException(); - - public string CreateAutomaticBackup(CancellationToken cancellationToken = default) => - throw new NotSupportedException(); - - public Task RestoreBackupAsync(string sourcePath, CancellationToken cancellationToken = default) => - throw new NotSupportedException(); - - private static ImportInspection Supported() => - new(ArchiveFormat.Current, ArchiveKind.AutomaticBackup, "v3.0.0", 1, 1, [], []); - } -} diff --git a/SecRandom.Core.Tests/SettingsIntegrityServiceTests.cs b/SecRandom.Core.Tests/SettingsIntegrityServiceTests.cs deleted file mode 100644 index 552e070bc..000000000 --- a/SecRandom.Core.Tests/SettingsIntegrityServiceTests.cs +++ /dev/null @@ -1,203 +0,0 @@ -using System.Security.Cryptography; -using System.Text.Json; -using Microsoft.Extensions.Logging.Abstractions; -using SecRandom.Core.Abstraction; -using SecRandom.Core.Models; -using SecRandom.Core.Models.SubConfigs; -using SecRandom.Core.Services.Config; -using SecRandom.Services.Security; - -namespace SecRandom.Core.Tests; - -public sealed class SettingsIntegrityServiceTests : IDisposable -{ - private readonly string _temporaryRoot = Path.Combine(Path.GetTempPath(), "SecRandom", "settings-integrity-tests", Guid.NewGuid().ToString("N")); - - [Fact] - public void Save_WhenTheCheckIsEnabled_RecordsTheWholeFileFingerprint() - { - var fixture = CreateFixture(); - fixture.SecuritySettings.SettingsIntegrityCheckEnabled = true; - - fixture.Handler.Save(); - - var record = Assert.IsType(fixture.Store.LoadMetadata().SettingsIntegrity); - Assert.Equal(ComputeDigest(fixture.ConfigPath), record.Digest); - Assert.False(string.IsNullOrWhiteSpace(record.RecordedAppVersion)); - Assert.Equal(1, record.Generation); - Assert.False(fixture.Service.GetPendingMismatch().HasValue); - } - - [Fact] - public void GetPendingMismatch_WhenTheFileChangesOutsideTheApp_ReportsTheRecordedTime() - { - var fixture = CreateFixture(); - fixture.SecuritySettings.SettingsIntegrityCheckEnabled = true; - fixture.Handler.Save(); - var before = fixture.Store.LoadMetadata().SettingsIntegrity; - - File.AppendAllText(fixture.ConfigPath, Environment.NewLine); - - var mismatch = fixture.Service.GetPendingMismatch(); - Assert.True(mismatch.HasValue); - Assert.Equal(before!.RecordedAtUtc, mismatch.Value.RecordedAtUtc); - Assert.NotNull(mismatch.Value.FileModifiedAtUtc); - } - - [Fact] - public void AcceptCurrentFile_AfterAnExternalChange_AdoptsTheCurrentFile() - { - var fixture = CreateFixture(); - fixture.SecuritySettings.SettingsIntegrityCheckEnabled = true; - fixture.Handler.Save(); - var original = fixture.Store.LoadMetadata().SettingsIntegrity; - File.AppendAllText(fixture.ConfigPath, Environment.NewLine); - Assert.True(fixture.Service.GetPendingMismatch().HasValue); - - fixture.Service.AcceptCurrentFile(); - - var record = Assert.IsType(fixture.Store.LoadMetadata().SettingsIntegrity); - Assert.Equal(ComputeDigest(fixture.ConfigPath), record.Digest); - Assert.Equal(original!.Generation + 1, record.Generation); - Assert.False(fixture.Service.GetPendingMismatch().HasValue); - } - - [Fact] - public void Save_WhenTheCheckIsDisabled_ClearsTheFingerprint() - { - var fixture = CreateFixture(); - fixture.SecuritySettings.SettingsIntegrityCheckEnabled = true; - fixture.Handler.Save(); - Assert.True(fixture.Service.IsEnabled); - - fixture.SecuritySettings.SettingsIntegrityCheckEnabled = false; - fixture.Handler.Save(); - - Assert.False(fixture.Service.IsEnabled); - Assert.Null(fixture.Store.LoadMetadata().SettingsIntegrity); - Assert.False(fixture.Service.GetPendingMismatch().HasValue); - } - - [Fact] - public void GetPendingMismatch_WhenTheFileIsMissing_ReportsAMismatchInsteadOfPassing() - { - var fixture = CreateFixture(); - fixture.SecuritySettings.SettingsIntegrityCheckEnabled = true; - fixture.Handler.Save(); - - File.Delete(fixture.ConfigPath); - - Assert.True(fixture.Service.GetPendingMismatch().HasValue); - } - - [Fact] - public void Save_WhenNoSecurityPasswordExists_KeepsTheCheckUnavailable() - { - var fixture = CreateFixture(createCredentials: false); - fixture.SecuritySettings.SettingsIntegrityCheckEnabled = true; - - fixture.Handler.Save(); - - Assert.False(fixture.Service.IsEnabled); - Assert.Null(fixture.Store.LoadMetadata().SettingsIntegrity); - } - - [Fact] - public void SaveSecuritySettings_WhenTheCheckIsEnabled_RecordsTheWholeFileFingerprint() - { - var fixture = CreateFixture(); - fixture.Handler.Save(); - - // 开关自己住在加密的安全设置里:单独改它也要刷新指纹,否则开关打开后根本不会有记录, - // 启动时 GetPendingMismatch 永远返回 null,校验等于没开。 - fixture.SecuritySettings.SettingsIntegrityCheckEnabled = true; - fixture.SettingsStore.Save(); - - var record = Assert.IsType(fixture.Store.LoadMetadata().SettingsIntegrity); - Assert.Equal(ComputeDigest(fixture.ConfigPath), record.Digest); - Assert.True(fixture.Service.IsEnabled); - } - - [Fact] - public void SaveSecuritySettings_WhenTheCheckIsDisabled_ClearsTheFingerprint() - { - var fixture = CreateFixture(); - fixture.Handler.Save(); - fixture.SecuritySettings.SettingsIntegrityCheckEnabled = true; - fixture.SettingsStore.Save(); - Assert.True(fixture.Service.IsEnabled); - - fixture.SecuritySettings.SettingsIntegrityCheckEnabled = false; - fixture.SettingsStore.Save(); - - Assert.False(fixture.Service.IsEnabled); - Assert.Null(fixture.Store.LoadMetadata().SettingsIntegrity); - } - - public void Dispose() - { - if (Directory.Exists(_temporaryRoot)) - Directory.Delete(_temporaryRoot, recursive: true); - } - - private SettingsIntegrityFixture CreateFixture(bool createCredentials = true) - { - Directory.CreateDirectory(_temporaryRoot); - var directory = Path.Combine(_temporaryRoot, Guid.NewGuid().ToString("N")); - Directory.CreateDirectory(directory); - var configPath = Path.Combine(directory, "settings.json"); - var handler = new MainConfigHandler( - NullLogger.Instance, - new FileBackedConfigService(configPath)); - var store = new SecurityCredentialStore( - Path.Combine(directory, "credentials.json"), - CredentialKdfParameters.Test); - if (createCredentials) - { - using var context = store.Create("secret1"); - store.Save(context); - } - - var securitySettings = new SecuritySettingsStore( - Path.Combine(directory, "security-settings", "settings.json"), - handler, - store, - NullLogger.Instance); - var service = new SettingsIntegrityService( - handler, - securitySettings, - store, - NullLogger.Instance, - configPath); - return new SettingsIntegrityFixture(handler, store, securitySettings, service, configPath); - } - - private static string ComputeDigest(string path) => - Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(path))); - - private sealed record SettingsIntegrityFixture( - MainConfigHandler Handler, - SecurityCredentialStore Store, - SecuritySettingsStore SettingsStore, - SettingsIntegrityService Service, - string ConfigPath) - { - public SecuritySettingsConfig SecuritySettings => SettingsStore.Data; - } - - private sealed class FileBackedConfigService(string path) : ConfigServiceBase - { - public override bool IsConfigExists(T fallback) => File.Exists(path); - - public override T LoadConfig(T fallback) => fallback; - - public override void SaveConfig(T config) => - File.WriteAllText(path, JsonSerializer.Serialize(config, JsonOptions)); - - public override void DeleteConfig(T config) - { - if (File.Exists(path)) - File.Delete(path); - } - } -} diff --git a/SecRandom.Core.Tests/UserFeedbackServiceTests.cs b/SecRandom.Core.Tests/UserFeedbackServiceTests.cs index 859873dce..65508dfdb 100644 --- a/SecRandom.Core.Tests/UserFeedbackServiceTests.cs +++ b/SecRandom.Core.Tests/UserFeedbackServiceTests.cs @@ -161,14 +161,10 @@ public Task ExportDiagnosticAsync( public Task ExportSettingsAsync(string destinationPath, CancellationToken cancellationToken = default) => throw new NotSupportedException(); public Task ExportAllDataAsync(string destinationPath, CancellationToken cancellationToken = default) => throw new NotSupportedException(); - public Task ExportCloudBackupAsync(string destinationPath, CancellationToken cancellationToken = default) => throw new NotSupportedException(); - public IReadOnlyList GetCloudBackupRoots() => throw new NotSupportedException(); public Task InspectSettingsAsync(string sourcePath, CancellationToken cancellationToken = default) => throw new NotSupportedException(); public Task InspectAllDataAsync(string sourcePath, CancellationToken cancellationToken = default) => throw new NotSupportedException(); - public Task InspectCloudBackupAsync(string sourcePath, CancellationToken cancellationToken = default) => throw new NotSupportedException(); public Task ImportSettingsAsync(string sourcePath, CancellationToken cancellationToken = default) => throw new NotSupportedException(); public Task ImportAllDataAsync(string sourcePath, CancellationToken cancellationToken = default) => throw new NotSupportedException(); - public Task ImportCloudBackupAsync(string sourcePath, CancellationToken cancellationToken = default) => throw new NotSupportedException(); public string CreateManualBackup(IReadOnlyCollection roots) => throw new NotSupportedException(); public string CreateAutomaticBackup(CancellationToken cancellationToken = default) => throw new NotSupportedException(); public Task RestoreBackupAsync(string sourcePath, CancellationToken cancellationToken = default) => throw new NotSupportedException(); diff --git a/SecRandom.Core/AGENTS.md b/SecRandom.Core/AGENTS.md index e777453aa..1d2117dc2 100644 --- a/SecRandom.Core/AGENTS.md +++ b/SecRandom.Core/AGENTS.md @@ -28,6 +28,7 @@ SecRandom.Core/ ├── StylesBase.axaml # Shared style hub imported by app ├── Services/Draw/ # Fair/random draw engine, filters, commit coordinator, shared repeat/candidate rules ├── Services/Archive/ # Platform-neutral v3 backup/archive engine (DataArchiveService + post-import hooks) +├── Services/DataRoot/ # Data-root migration journal, copy/verify engine, and root-relative path rewriter ├── Services/Config/ # Config handlers over Shared config models ├── Services/Profiles/ # Host-internal profile persistence runtime shared by desktop/mobile ├── Services/HistoryStore/ # Per-profile SQLite history storage (paths + database, with legacy JSON import) @@ -55,7 +56,7 @@ SecRandom.Core/ | Page registration | `Extensions/Registry/` | `AddMainPage`, `AddSettingsPage`, group/separator helpers. | | Navigation registry | `Services/PagesRegistryService.cs` | Static main/settings/group collections. | | Attached-settings registry | `Services/AttachedSettingsRegistryService.cs` | Static attached-settings control collections. | -| Draw algorithm | `Services/Draw/DrawEngine*.cs`, `WeightedDrawEngine.cs`, `CryptoRandomSource.cs` | Fairness, mandatory average-gap candidate gate, share-debt weighted sampling (dimension horizon scales with batch size), filters; history lookup uses `RecordId`. Repeat thresholds and candidate filtering live in the shared `DrawRepeatPolicy`/`DrawCandidateFilter`. | +| Draw algorithm | `Services/Draw/DrawEngine*.cs`, `WeightedDrawEngine.cs`, `CryptoRandomSource.cs` | Fairness, mode-dependent average-gap handling (`FairDrawMode.UniformFirst` keeps the hard candidate gate, `FairDrawMode.RandomFirst` drops the gate and zeroes weights above the mean + slack), share-debt weighted sampling (dimension horizon scales with batch size), filters; history lookup uses `RecordId`. Repeat thresholds and candidate filtering live in the shared `DrawRepeatPolicy`/`DrawCandidateFilter`. | | Draw commit boundary | `Services/Draw/DrawCommitCoordinator.cs`, `Abstraction/Services/IDrawCommitService.cs` | Single-`DrawRoundId` transactional commit: temporary records before history, failure snapshot compensation, serialized commit gate. | | Config handlers | `Services/Config/` | `FileConfigService`, `MainConfigHandler`, and `ProfileConfigs` implement host-internal persistence. `ConfigHandlerBase.Saved` fires after a successful write so the app layer can refresh the settings-file integrity fingerprint. Everything stays JSON except profile history: `ConfigHandlerBase` routes all reads/writes through three virtual seams (`LoadData`/`SaveData`/`DeleteData`), and `StudentHistoryConfig`/`PrizeHistoryConfig` override them to reach `Services/HistoryStore/` instead. | | Profile history storage | `Services/HistoryStore/ProfileHistoryPaths.cs`, `ProfileHistoryDatabase.cs` | Host-internal SQLite storage for `StudentHistory`/`PrizeHistory` (`data/history/{roll_call_history,lottery_history}/{name}.srhdb`), because a history file grows without bound while the JSON handler rewrote the whole file on every save (three times per draw). `ProfileHistoryPaths` owns every path decision (database, not-yet-migrated JSON, `.json.migrated` backup, `-wal`/`-shm`, enumerate/rename/delete) — never build a `{name}.json` history path by hand. `ProfileHistoryDatabase` reads a whole profile and saves incrementally: `meta`/`groups`/`counters` are small and rewritten, while each record row carries a content fingerprint (`row_hash`) compared per member, so a draw only inserts the changed member's rows and never rewrites the rest. Saving runs in one transaction, which is why history does not use the temp-file + atomic-replace pattern. It also owns the transparent upgrade: a missing database with a legacy `{name}.json` present is imported on first read and the JSON is renamed to `{name}.json.migrated`, which no `*.json` reader matches. A build that predates this storage only understands history JSON, so a downgrade needs those backups renamed back to `{name}.json` by hand; that is the one manual step the upgrade has. | @@ -68,7 +69,7 @@ SecRandom.Core/ | Statistics reporting entrance | `Services/Stats/PlatformStatsApi.cs` | The one aggregate SECTL statistics entrance `PlatformStatsApi.ReportUri` (`POST /api/stats/report`) plus the pinned `BaseUrl`/`PlatformId`. Every reporting service posts here and never to a per-type endpoint; the four old endpoints (`/api/stats/online`, `/api/stats/usage/increment`, `/api/stats/version`, `/api/fields/values`) are compatibility-only and must not be reintroduced. The service judges the report type from the payload keys and stops at the first hit — (1) `field_key` **and** `value` → field, (2) `version`/`app_version` → version, (3) `metrics`/`increments`/`usage`/`delta`/`metric_key` → usage, (4) anything else carrying `platform_id`/`device_uuid` → online — so the payload shapes below are load-bearing: a stray `value`, `version`, or `delta` silently books the number under another figure instead of failing. `PlatformStatsReportEntranceTests` pins the entrance and the judgment order. | | Usage statistics counters | `Services/Stats/UsageMetricCounter.cs` | Platform-neutral counters for the current local day plus the pinned SECTL increment payload shape (`platform_id`/`field_key`/`delta`; no time field, because the service side buckets by its own receive time, and deliberately no `value`, which the aggregate entrance would judge as a last-value field report). Only the `daily_*` field keys are reported; the weekly/monthly/lifetime figures are service-side. Pure state: the app-layer `PlatformUsageReportService` owns persistence, debounce, and HTTP, so the counting rules stay testable. | | Version usage payload | `Services/Stats/VersionUsageReportPayload.cs` | Pure payload for the SECTL version counter, posted to the aggregate entrance where the presence of `version` is what makes it a version report: `platform_id`/`version`/`device_uuid` with the API's pinned field names. The device UUID is required and must parse as a UUID; the account identity the API also accepts (`user_id`) is deliberately never sent, so a version figure cannot be tied to a SECTL account, and the API's version rule (1–64 chars, alphanumeric first char, allowed separators) is validated locally so an unusable build tag is skipped instead of coming back as `invalid_request`. The app-layer `PlatformVersionReportService` owns the single startup request. | -| Data archive runtime | `Services/Archive/` | `DataArchiveService` (v3 settings/data transfer, manifest/SHA-256, staging commit/rollback, snapshots) with `IArchivePostImportHooks` for platform follow-up and `IArchivePreImportGuard` for the pre-commit authorization check (`AuthorizeImport()`: one fresh verification whenever protection is active, asked for every archive kind — the protection switches are no longer inside the archive); registered by `AddCoreRuntimeServices`. `ArchiveKind.CloudBackup` plus the `CloudBackupRoots` ceiling and `ResolveCloudBackupRoots(BackupConfig)` define the account cloud-sync archive, and `CloudBackupPackage` owns its part/manifest format, in which schema 1 is the only version and the removed encryption feature's `-enc` name marker is still parsed so a legacy package is recognised and refused. | +| Data root migration | `Services/DataRoot/` | Two-process, restart-driven relocation of the desktop data root: `DataRootMigrationJournal` (`data-root-journal.json`, states Pending→Copying→Verifying→Committing→Completed/Failed/Cancelled) is written by the settings page before the restart and read by the migration window, `DataRootMigrationEngine` validates (target must not equal, nest inside, or contain the source, must not sit inside the running payload, must be absent or empty), copies into a same-volume staging directory `.migrating-` (skipping `updates/**`, `.migrated-*`, `*.tmp`, `*.lock`), verifies lengths plus SHA-256 for files ≤ 4 MiB (larger media compare length + last write time), rewrites root-absolute references, renames staging onto the target and only then writes the anchor; the source is kept as `.migrated-`. The anchor write is the single commit point — if it fails the target moves back to staging and the source is left untouched. `DataRootPathRewriter` only touches `ImagePath` in `list/**/*.json` and `path`/`proofPath` in `proofs/attestation-queue.json`, preserving each file's original formatting. | `DataArchiveService` (v3 settings/data transfer, manifest/SHA-256, staging commit/rollback, snapshots) with `IArchivePostImportHooks` for platform follow-up and `IArchivePreImportGuard` for the pre-commit authorization check (`AuthorizeImport()`: one fresh verification whenever protection is active, asked for every archive kind — the protection switches are no longer inside the archive); registered by `AddCoreRuntimeServices`. `ArchiveKind.CloudBackup` is kept as a legacy value only, so a cloud archive produced by an older build is recognised and rejected on import. | | Roll-call algorithms | `Abstraction/Services/IRollCallAlgorithm.cs`, `Services/Draw/RollCallAlgorithms.cs` | Host-registered fair/random weighting strategies with stable Id/Name; winner selection and verification remain in the existing DrawEngine/verification pipeline. | | Lottery algorithms | `Abstraction/Services/ILotteryAlgorithm.cs`, `Services/Draw/RollCallAlgorithms.cs` | Host-registered inventory/weighted prize candidate strategies with stable Id/Name; assignment and transactional commit remain in the app draw service. | | Control node protocol | `Services/ControlNode/` | Transport-agnostic v4.1 engine (details: `../SECTL-auth/docs/control-center-protocol-v4.md`): `ControlNodeSession` owns handshake, server-provided heartbeat, two-frame receipts (`cmd.ack` then `cmd.result`, both echoing `command_id`), per-command order — `expires_at` (Unix ms) expiry first (expired commands are dropped and never replayed), device-owned local switch, capability check, idempotency ledger, ack before execution, result after — plus `desired_state` convergence on a strictly increasing 64-bit `revision` (missing `draw_locked` means locked) and `class.select`/`class.release` occupancy so the console can see this device in a class. `ControlNodeClient` owns the reconnect loop (1 s→60 s with jitter; non-retryable codes become `Blocked`), `FileControlNodeStateStore` persists `data/config/control/node-state.json` by atomic replace, and `ControlEndpointPolicy` allows `wss://` or plaintext `ws://` only to loopback. | @@ -103,7 +104,6 @@ SecRandom.Core/ files. - `FileConfigService`, `ProfileService`, `DrawTemporaryRecordService`, and the concrete feature-availability service are private implementation details behind `AddCoreRuntimeServices()`. Desktop and mobile call that registration extension from their composition roots while exposing only the established narrow contracts to consumers. - `Services/Archive/` owns all v3 settings/data ZIP and settings-JSON transfer: `DataArchiveService` performs producer-version/manifest/SHA-256 validation, staging commit/rollback, and mandatory pre-import snapshots. The producer-version gate compares only the numeric core's major after stripping the optional `v` prefix and any SemVer pre-release/build suffix, because `producer_version` is the raw `GlobalConstants.Version` and a pre-release build (`v3.0.0-alpha.2`) must accept its own exports. Platform-specific follow-up stays behind `IArchivePostImportHooks`; `AddCoreRuntimeServices()` registers the Null hooks and shells override them (desktop: `DesktopArchivePostImportHooks`). Every import and restore also asks `IArchivePreImportGuard` before the snapshot and the commit. The gate no longer receives a candidate configuration, because the protection switches have moved out of `settings.json` into the encrypted `data/config/security/settings.json` that no archive can reach: `AddCoreRuntimeServices()` registers `NullArchivePreImportGuard` and the desktop shell overrides it with `SecurityArchivePreImportGuard`, whose `AuthorizeImport()` asks the host for one fresh verification (no sudo state counts) whenever protection is active and rejects the import before anything is written when that verification fails or is cancelled. Importing a backup is still a whole-configuration replacement, which is why the gate stays; it is asked for every archive kind, including one that carries only lists and therefore no settings file. Export is deliberately not gated — automatic and cloud backups run with no dialog available. The startup settings-integrity auto-restore reads its own backup ZIP without going through this engine and is deliberately outside the gate (it runs before any UI exists and is already anchored on the integrity fingerprint). -- Account cloud sync reuses that engine: `ExportCloudBackupAsync` writes an `ArchiveKind.CloudBackup` archive whose root set is resolved by `ResolveCloudBackupRoots(BackupConfig)` from the dedicated `CloudInclude*` selection and capped by `CloudBackupRoots` (no device identity, voice cache, draw proofs, theme resources, or logs — the cloud content list has no row for any of them), `InspectCloudBackupAsync`/`ImportCloudBackupAsync` accept only that kind, and the import filters `config/device-uuid.json` out of its commit roots so a crafted cloud archive can never re-identify the device. `CloudBackupPackage` is UI-free, transport-free, and key-free: it owns part naming, backup-id generation and safety, the optional device alias a backup id carries (`BuildDeviceTag`/`CreateBackupId`/`TryGetDeviceTag`), splitting, manifest validation, and whole-archive verification, while upload/download/HTTP and the alias choice (`BackupConfig.CloudDeviceAlias`) stay in the app layer. Its format has exactly one supported version: schema 1, where the parts carry the v3 archive itself and `ArchiveBytes`/`ArchiveSha256` describe that payload. Client-side encryption was removed, so no key material exists anywhere in the format; the removed feature's `-enc` name marker is still parsed so a schema-2 package uploaded by an older build is recognised and rejected by the schema check instead of being mis-grouped as a current backup. - IPC parser code is UI-free and must reject ambiguous routes, malformed percent escapes, control characters, oversized frames, and unsupported schemes. Keep route execution in the app layer. - File logging should keep user-facing log messages in Chinese for app events. Avoid logging student/prize names or full config payloads; prefer counts, status, file names, and operation names. - Application data that SecRandom itself may hold open must be read through `Helpers/SharedFileReader.cs` (share `ReadWrite` + `Delete`). The live `data/logs/log-*.log` is held by `FileLoggerProvider` as `FileShare.Read` for the whole session, so a plain `File.OpenRead`/`File.ReadAllText` is refused by Windows and used to fail a whole all-data export while diagnostics silently dropped the log; when a read really fails, the caller must report it (count + file names) instead of skipping it. Derived files such as the compressed previous log are written to a temporary file and moved into place, never created in place. diff --git a/SecRandom.Core/Enums/Configs/SettingsIntegrityAction.cs b/SecRandom.Core/Enums/Configs/SettingsIntegrityAction.cs deleted file mode 100644 index d787bab11..000000000 --- a/SecRandom.Core/Enums/Configs/SettingsIntegrityAction.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace SecRandom.Core.Enums.Configs; - -/// -/// 设置文件防篡改校验在启动时发现改动后的处理方式。 -/// -public enum SettingsIntegrityAction -{ - /// 要求用安全密码确认当前设置文件之后才能继续启动,这是原有行为。 - Confirm, - - /// 自动用最近一次备份中的设置文件覆盖当前文件,然后重启应用。 - AutoRestore -} diff --git a/SecRandom.Core/Enums/Configs/SettingsIntegrityRestoreSource.cs b/SecRandom.Core/Enums/Configs/SettingsIntegrityRestoreSource.cs deleted file mode 100644 index 4ee930318..000000000 --- a/SecRandom.Core/Enums/Configs/SettingsIntegrityRestoreSource.cs +++ /dev/null @@ -1,16 +0,0 @@ -namespace SecRandom.Core.Enums.Configs; - -/// -/// 自动恢复设置文件时依次尝试的备份来源。 -/// -public enum SettingsIntegrityRestoreSource -{ - /// 只使用本机 data/backup 中的备份。 - Local, - - /// 先本地备份,本地没有包含设置文件的可用备份时再使用本机上传的云端备份。 - LocalThenCloud, - - /// 先本机上传的云端备份,未登录或云端不可用时再使用本地备份。 - CloudThenLocal -} diff --git a/SecRandom.Core/Models/SubConfigs/General/BackupConfig.cs b/SecRandom.Core/Models/SubConfigs/General/BackupConfig.cs index 8e785e4f7..529f2fd51 100644 --- a/SecRandom.Core/Models/SubConfigs/General/BackupConfig.cs +++ b/SecRandom.Core/Models/SubConfigs/General/BackupConfig.cs @@ -8,38 +8,6 @@ public partial class BackupConfig : ObservableObject [ObservableProperty] private int _autoBackupIntervalDays = 7; [ObservableProperty] private int _autoBackupMaxCount = 16; - /// - /// Cloud backup stays opt-in: it uploads the account's data to SECTL on its own schedule, so - /// an existing installation must not start doing that just because the app updated. - /// - [ObservableProperty] private bool _cloudAutoBackupEnabled = false; - [ObservableProperty] private int _cloudAutoBackupIntervalDays = 7; - [ObservableProperty] private int _cloudAutoBackupMaxCount = 5; - - /// - /// Device alias stamped into every cloud backup id, so several signed-in devices can tell - /// their own backups apart in the cloud list and keep their own retention budget. It is a - /// user-visible display label rather than a device identity, so the device UUID still never - /// reaches the cloud; empty means the host name is used. - /// - [ObservableProperty] private string _cloudDeviceAlias = string.Empty; - - /// - /// Cloud backup content is selected separately from the local backup, and it is shorter on - /// purpose: logs, the device identity, the generated voice cache, and theme resources have no - /// row because a cloud archive may never carry them. Images stay off by default because - /// member/prize pictures are what fills the account quota fastest, and draw proofs stay off by - /// default because uploading them is a deliberate choice — they are the only copy of the local - /// evidence chain once a proof has been deleted locally. - /// - [ObservableProperty] private bool _cloudIncludeConfig = true; - [ObservableProperty] private bool _cloudIncludeList = true; - [ObservableProperty] private bool _cloudIncludeHistory = true; - [ObservableProperty] private bool _cloudIncludeAudio = false; - [ObservableProperty] private bool _cloudIncludeCses = true; - [ObservableProperty] private bool _cloudIncludeImages = false; - [ObservableProperty] private bool _cloudIncludeProofs = false; - [ObservableProperty] private bool _includeConfig = true; [ObservableProperty] private bool _includeList = true; [ObservableProperty] private bool _includeHistory = true; diff --git a/SecRandom.Core/Models/SubConfigs/SecuritySettingsConfig.cs b/SecRandom.Core/Models/SubConfigs/SecuritySettingsConfig.cs index 79fe9f6ce..fd4a303bb 100644 --- a/SecRandom.Core/Models/SubConfigs/SecuritySettingsConfig.cs +++ b/SecRandom.Core/Models/SubConfigs/SecuritySettingsConfig.cs @@ -1,5 +1,4 @@ using CommunityToolkit.Mvvm.ComponentModel; -using SecRandom.Core.Enums.Configs; namespace SecRandom.Core.Models.SubConfigs; @@ -12,23 +11,6 @@ public partial class SecuritySettingsConfig : ObservableObject [ObservableProperty] private bool _requireAllSelectedFactors; [ObservableProperty] private bool _allowSettingsPreview; - /// - /// 开启后由 SettingsIntegrityService 记录整份 settings.json 的指纹, - /// 并在启动时校验该文件是否被程序之外的改动修改过。 - /// - [ObservableProperty] private bool _settingsIntegrityCheckEnabled; - - /// - /// 校验发现改动后要执行的操作;默认仍然是原有的「用安全密码确认后继续」。 - /// - [ObservableProperty] private SettingsIntegrityAction _settingsIntegrityAction = SettingsIntegrityAction.Confirm; - - /// - /// 自动恢复时依次尝试的备份来源,与处理方式分开配置,因为来源只影响自动恢复这一次操作。 - /// - [ObservableProperty] - private SettingsIntegrityRestoreSource _settingsIntegrityRestoreSource = SettingsIntegrityRestoreSource.Local; - [ObservableProperty] private bool _protectOpenSettings; [ObservableProperty] private bool _protectToggleMainWindow; [ObservableProperty] private bool _protectToggleFloatingWindow; diff --git a/SecRandom.Core/Services/Archive/CloudBackupPackage.cs b/SecRandom.Core/Services/Archive/CloudBackupPackage.cs deleted file mode 100644 index d15a19e7f..000000000 --- a/SecRandom.Core/Services/Archive/CloudBackupPackage.cs +++ /dev/null @@ -1,411 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Security.Cryptography; -using System.Text; -using System.Text.Json; -using System.Text.Json.Serialization; -using System.Text.RegularExpressions; -using SecRandom.Core.Abstraction; - -namespace SecRandom.Core.Services.Archive; - -/// -/// Cloud backup split package: the account cloud service keeps one backup as several small -/// parts plus a trailing manifest. Splitting keeps every upload request well below the -/// cloud-function request-body limit while the manifest carries the per-part and whole-archive -/// SHA-256 values needed to rebuild one verified SecRandom v3 archive. -/// -public static partial class CloudBackupPackage -{ - public const string Format = "secrandom-cloud-backup"; - - /// The only supported package schema: the parts carry the v3 ZIP archive itself. - public const int SchemaVersion = 1; - - public const string FilePrefix = "SecRandom-cloud-"; - public const string PartExtension = ".srpart"; - public const string ManifestSuffix = "-manifest.json"; - - /// - /// Marker the removed client-side encryption feature wrote into every file name of a schema-2 - /// package. The format no longer produces it, but the listing still recognises it so backups - /// uploaded by an older build stay visible as a separate, unrestorable entry instead of being - /// mis-grouped as a current backup. - /// - public const string LegacyEncryptionMarker = "-enc"; - - /// - /// Longest device alias a backup id carries. The alias is part of every cloud file name, so it - /// stays short enough for the whole id to remain inside 's - /// 64-character limit and readable in the cloud dashboard listing. - /// - public const int MaxDeviceTagLength = 16; - - /// - /// 512 KiB of archive bytes per part. The upload body is a base64 JSON payload, so one part - /// stays around 700 KiB and remains safely inside the conservative 1 MiB request budget of - /// the SECTL cloud function origin. - /// - public const int DefaultPartBytes = 512 * 1024; - - /// Conservative request-body budget; the cloud function origin limits bodies near 1 MiB. - public const long MaxUploadBodyBytes = 1L * 1024 * 1024; - - private const int MaxPartCount = 64; - private const long JsonEnvelopeOverheadBytes = 1024; - private const long MaxArchiveBytes = 16L * 1024 * 1024; - - private static JsonSerializerOptions ManifestJsonOptions => ConfigServiceBase.JsonOptions; - - [GeneratedRegex("^(?.+)-p(?\\d{2,3})of(?\\d{2,3})$", RegexOptions.CultureInvariant)] - private static partial Regex PartNamePattern(); - - /// - /// Shape of an id this package generates: a timestamp, the random suffix, and the optional - /// device alias. Only ids matching it report a device alias, so a foreign id uploaded by an - /// older build or crafted through the cloud dashboard is never attributed to a device. - /// - [GeneratedRegex("^\\d{8}-\\d{6}-[0-9a-f]{8}(?_[A-Za-z0-9-]{1,16})?$", RegexOptions.CultureInvariant)] - private static partial Regex BackupIdPattern(); - - public static string CreateBackupId(DateTime utcNow, string? deviceTag = null) - { - var id = $"{utcNow:yyyyMMdd-HHmmss}-{Convert.ToHexString(RandomNumberGenerator.GetBytes(4)).ToLowerInvariant()}"; - var tag = NormalizeDeviceTag(deviceTag); - return tag.Length == 0 ? id : $"{id}_{tag}"; - } - - /// - /// Builds the alias stamped on this device's backups. A configured alias wins; otherwise the - /// host name is used, and a host name without ASCII-safe characters falls back to a short - /// digest so its backups stay attributable. An empty result means the id carries no alias. - /// - public static string BuildDeviceTag(string? deviceName) - { - var normalized = NormalizeDeviceTag(deviceName); - if (normalized.Length > 0) - return normalized; - - return string.IsNullOrWhiteSpace(deviceName) - ? string.Empty - : Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(deviceName.Trim())))[..4].ToLowerInvariant(); - } - - /// Reads the alias this package encoded into a backup id. - public static bool TryGetDeviceTag(string? backupId, out string deviceTag) - { - deviceTag = string.Empty; - if (string.IsNullOrWhiteSpace(backupId)) - return false; - - var match = BackupIdPattern().Match(backupId); - if (!match.Success || !match.Groups["tag"].Success) - return false; - - deviceTag = match.Groups["tag"].Value[1..]; - return true; - } - - private static string NormalizeDeviceTag(string? value) - { - if (string.IsNullOrWhiteSpace(value)) - return string.Empty; - - var builder = new StringBuilder(MaxDeviceTagLength); - foreach (var character in value.Trim()) - { - if (!char.IsAsciiLetterOrDigit(character) && character != '-') - continue; - builder.Append(character); - if (builder.Length == MaxDeviceTagLength) - break; - } - - return builder.ToString(); - } - - public static string BuildPartName(string backupId, int index, int partCount) => - $"{FilePrefix}{backupId}-p{index:D2}of{partCount:D2}{PartExtension}"; - - public static string BuildManifestName(string backupId) => $"{FilePrefix}{backupId}{ManifestSuffix}"; - - public static string BuildArchiveName(string backupId) => $"SecRandom_cloud_{backupId}.zip"; - - public static bool IsCloudBackupFileName(string? fileName) => - !string.IsNullOrWhiteSpace(fileName) && fileName.StartsWith(FilePrefix, StringComparison.Ordinal); - - /// - /// Parses a cloud file name produced by this package format. Foreign file names return false - /// so personal-cloud listings can keep unrelated platform files out of the backup list. - /// reports the removed encryption feature's name marker: such a - /// backup was sealed with a passphrase this build can no longer derive a key for, so the caller - /// keeps it visible but not restorable. - /// - public static bool TryParseFileName(string? fileName, out string backupId, out int partIndex, out int partCount, - out bool isManifest, out bool isEncrypted) - { - backupId = string.Empty; - partIndex = 0; - partCount = 0; - isManifest = false; - isEncrypted = false; - if (!IsCloudBackupFileName(fileName)) - return false; - - var remainder = StripLegacyEncryptionMarker(fileName![FilePrefix.Length..], out isEncrypted); - if (remainder.EndsWith(ManifestSuffix, StringComparison.Ordinal)) - { - backupId = remainder[..^ManifestSuffix.Length]; - isManifest = true; - return IsSafeBackupId(backupId); - } - - if (!remainder.EndsWith(PartExtension, StringComparison.Ordinal)) - return false; - - var match = PartNamePattern().Match(remainder[..^PartExtension.Length]); - if (!match.Success) - return false; - - backupId = match.Groups["id"].Value; - return IsSafeBackupId(backupId) - && int.TryParse(match.Groups["index"].Value, out partIndex) - && int.TryParse(match.Groups["count"].Value, out partCount) - && partIndex >= 1 && partCount >= 1 && partIndex <= partCount; - } - - /// Parses a cloud file name without reporting its legacy encryption marker. - public static bool TryParseFileName(string? fileName, out string backupId, out int partIndex, out int partCount, - out bool isManifest) => - TryParseFileName(fileName, out backupId, out partIndex, out partCount, out isManifest, out _); - - /// - /// Splits the removed feature's marker off a file name remainder, so a package uploaded by an - /// older build keeps its own backup id and is still recognised (and refused) by name. - /// - private static string StripLegacyEncryptionMarker(string remainder, out bool isEncrypted) - { - isEncrypted = false; - var suffixLength = remainder.EndsWith(ManifestSuffix, StringComparison.Ordinal) - ? ManifestSuffix.Length - : remainder.EndsWith(PartExtension, StringComparison.Ordinal) - ? PartExtension.Length - : 0; - if (suffixLength == 0) - return remainder; - - var stem = remainder[..^suffixLength]; - if (!stem.EndsWith(LegacyEncryptionMarker, StringComparison.Ordinal)) - return remainder; - - isEncrypted = true; - return string.Concat(stem[..^LegacyEncryptionMarker.Length], remainder[^suffixLength..]); - } - - /// - /// A backup id comes from a cloud file name, which a user could craft through the web - /// dashboard. It is used in local staging paths, so only plain id characters are accepted. - /// - public static bool IsSafeBackupId(string? backupId) => - !string.IsNullOrWhiteSpace(backupId) && backupId.Length <= 64 && - !backupId.Contains("..", StringComparison.Ordinal) && - backupId.All(character => char.IsAsciiLetterOrDigit(character) || character is '-' or '_' or '.'); - - /// Splits archive bytes into ordered parts of at most bytes. - public static IReadOnlyList Slice(byte[] archive, int partBytes = DefaultPartBytes) - { - ArgumentNullException.ThrowIfNull(archive); - if (partBytes <= 0) - throw new ArgumentOutOfRangeException(nameof(partBytes)); - if (archive.Length == 0) - return [[]]; - - var parts = new List((archive.Length + partBytes - 1) / partBytes); - for (var offset = 0; offset < archive.Length; offset += partBytes) - { - var length = Math.Min(partBytes, archive.Length - offset); - var part = new byte[length]; - Buffer.BlockCopy(archive, offset, part, 0, length); - parts.Add(part); - } - - return parts; - } - - /// - /// Builds the manifest that describes the already-sliced parts of one backup. - /// is the byte sequence the parts were sliced from — the v3 ZIP - /// archive itself. and - /// always describe that payload, so per-part - /// verification stays a plain SHA-256 check. - /// - public static CloudBackupManifest BuildManifest(string backupId, IReadOnlyList parts, int partBytes, - IReadOnlyList roots, DateTime createdUtc, string producerVersion, byte[] payload) - { - ArgumentException.ThrowIfNullOrWhiteSpace(backupId); - ArgumentNullException.ThrowIfNull(parts); - ArgumentNullException.ThrowIfNull(payload); - if (parts.Count == 0) - throw new InvalidDataException("云端备份分片不能为空。"); - if (parts.Count > MaxPartCount) - throw new InvalidDataException("云端备份分片数量超过限制。"); - if (partBytes is <= 0 or > DefaultPartBytes || payload.LongLength > MaxArchiveBytes || - parts.Any(part => part is null || part.LongLength > partBytes)) - throw new InvalidDataException("云端备份分片或归档长度无效。"); - - var manifest = new CloudBackupManifest - { - Format = Format, - SchemaVersion = SchemaVersion, - ProducerVersion = producerVersion, - BackupId = backupId, - ArchiveName = BuildArchiveName(backupId), - ArchiveBytes = payload.LongLength, - ArchiveSha256 = Hash(payload), - PartBytes = partBytes, - CreatedUtc = createdUtc, - Roots = [.. roots], - Parts = [] - }; - - for (var index = 0; index < parts.Count; index++) - { - manifest.Parts.Add(new CloudBackupPart - { - Index = index + 1, - Name = BuildPartName(backupId, index + 1, parts.Count), - Length = parts[index].LongLength, - Sha256 = Hash(parts[index]) - }); - } - - ValidateManifest(manifest); - return manifest; - } - - /// - /// Validates a downloaded manifest and rebuilds the payload the parts describe. Any structural - /// problem, missing/reordered part, or hash mismatch aborts before an import can start. A - /// manifest written by the removed encryption feature (schema 2) is rejected here, because this - /// build holds no way to derive a key for it. - /// - public static byte[] MergeAndVerify(CloudBackupManifest manifest, IReadOnlyList parts) - { - ValidateManifest(manifest); - if (parts.Count != manifest.Parts.Count) - throw new InvalidDataException("云端备份分片数量与清单不一致。"); - - using var payload = new MemoryStream((int)manifest.ArchiveBytes); - for (var index = 0; index < manifest.Parts.Count; index++) - { - var expected = manifest.Parts[index]; - var actual = parts[index]; - if (actual.LongLength != expected.Length || !Hash(actual).Equals(expected.Sha256, StringComparison.OrdinalIgnoreCase)) - throw new InvalidDataException($"云端备份第 {expected.Index} 个分片校验失败。"); - payload.Write(actual); - } - - var merged = payload.ToArray(); - if (merged.LongLength != manifest.ArchiveBytes || - !Hash(merged).Equals(manifest.ArchiveSha256, StringComparison.OrdinalIgnoreCase)) - throw new InvalidDataException("云端备份归档校验失败。"); - return merged; - } - - public static void ValidateManifest(CloudBackupManifest? manifest) - { - if (manifest is null || manifest.Format != Format || manifest.SchemaVersion != SchemaVersion) - throw new InvalidDataException("云端备份清单格式不受支持。"); - if (manifest.Parts is null || !IsSafeBackupId(manifest.BackupId) || - !string.Equals(manifest.ArchiveName, BuildArchiveName(manifest.BackupId), StringComparison.Ordinal) || - manifest.Parts.Count is < 1 or > MaxPartCount) - throw new InvalidDataException("云端备份清单内容无效。"); - if (manifest.PartBytes is <= 0 or > DefaultPartBytes) - throw new InvalidDataException("云端备份清单的分片大小无效。"); - - for (var index = 0; index < manifest.Parts.Count; index++) - { - var part = manifest.Parts[index]; - if (part is null || part.Index != index + 1 || part.Length < 0 || part.Length > manifest.PartBytes || - !IsSha256(part.Sha256) || - !TryParseFileName(part.Name, out var partBackupId, out var partIndex, out var partCount, - out var isManifest, out var isLegacyEncrypted) || - isManifest || isLegacyEncrypted || - partBackupId != manifest.BackupId || partIndex != part.Index || partCount != manifest.Parts.Count) - throw new InvalidDataException("云端备份清单的分片描述无效。"); - } - - if (manifest.ArchiveBytes is < 0 or > MaxArchiveBytes || !IsSha256(manifest.ArchiveSha256)) - throw new InvalidDataException("云端备份清单的归档长度无效。"); - - long declaredPartBytes = 0; - foreach (var part in manifest.Parts) - { - if (part.Length > MaxArchiveBytes - declaredPartBytes) - throw new InvalidDataException("云端备份清单的归档长度无效。"); - declaredPartBytes += part.Length; - } - - if (declaredPartBytes != manifest.ArchiveBytes) - throw new InvalidDataException("云端备份清单的归档长度无效。"); - } - - public static CloudBackupManifest DeserializeManifest(byte[] content) - { - try - { - return JsonSerializer.Deserialize(content, ManifestJsonOptions) - ?? throw new InvalidDataException("云端备份清单为空。"); - } - catch (JsonException exception) - { - throw new InvalidDataException("云端备份清单无法解析。", exception); - } - } - - public static byte[] SerializeManifest(CloudBackupManifest manifest) => - Encoding.UTF8.GetBytes(JsonSerializer.Serialize(manifest, ManifestJsonOptions)); - - /// Rejects a part size whose base64 JSON upload body would exceed the request-body budget. - public static void EnsureUploadBodySize(int partBytes) - { - var base64Length = 4L * ((partBytes + 2) / 3); - if (base64Length + JsonEnvelopeOverheadBytes > MaxUploadBodyBytes) - throw new InvalidDataException("云端备份分片体积超过上传限制。"); - } - - private static bool IsSha256(string? value) => - value is { Length: 64 } && value.All(Uri.IsHexDigit); - - public static string Hash(byte[] content) => Convert.ToHexString(SHA256.HashData(content)); -} - -public sealed class CloudBackupManifest -{ - [JsonPropertyName("format")] public string Format { get; set; } = CloudBackupPackage.Format; - [JsonPropertyName("schema_version")] public int SchemaVersion { get; set; } = CloudBackupPackage.SchemaVersion; - [JsonPropertyName("producer_version")] public string ProducerVersion { get; set; } = string.Empty; - [JsonPropertyName("backup_id")] public string BackupId { get; set; } = string.Empty; - [JsonPropertyName("archive_name")] public string ArchiveName { get; set; } = string.Empty; - - /// Length of the payload the parts carry: the v3 ZIP archive itself. - [JsonPropertyName("archive_bytes")] public long ArchiveBytes { get; set; } - - /// SHA-256 of the payload the parts carry, so a rebuilt archive is verified before a restore. - [JsonPropertyName("archive_sha256")] public string ArchiveSha256 { get; set; } = string.Empty; - - [JsonPropertyName("part_bytes")] public int PartBytes { get; set; } - [JsonPropertyName("created_utc")] public DateTime CreatedUtc { get; set; } - [JsonPropertyName("roots")] public List Roots { get; set; } = []; - - [JsonPropertyName("parts")] public List Parts { get; set; } = []; -} - -public sealed class CloudBackupPart -{ - [JsonPropertyName("index")] public int Index { get; set; } - [JsonPropertyName("name")] public string Name { get; set; } = string.Empty; - [JsonPropertyName("length")] public long Length { get; set; } - [JsonPropertyName("sha256")] public string Sha256 { get; set; } = string.Empty; -} diff --git a/SecRandom.Core/Services/Archive/DataArchiveService.cs b/SecRandom.Core/Services/Archive/DataArchiveService.cs index cb0bec488..9143c5147 100644 --- a/SecRandom.Core/Services/Archive/DataArchiveService.cs +++ b/SecRandom.Core/Services/Archive/DataArchiveService.cs @@ -56,23 +56,7 @@ public sealed class DataArchiveService( "Language", "logs", "texts" ]; - /// - /// Hard ceiling for account cloud backups: the portable data a cloud archive may ever carry. - /// It deliberately omits the device identity, the generated voice cache, draw proofs, theme - /// resources, and logs, because a cloud archive must never re-identify another device or carry - /// regenerable/diagnostic payloads. Plugins, security credentials, and staging directories are - /// excluded by for every archive kind, and logs are never - /// committed by a restore either. - /// - public static readonly string[] CloudBackupRoots = - [ - "config/settings.json", "list", "history", "TEMP", "audio/music", "CSES", "images", "Language", "proofs", "texts" - ]; - - /// Cloud roots whose content has no row in the cloud backup-content selection. - private static readonly string[] AlwaysSelectedCloudRoots = ["TEMP", "Language"]; - - /// Device-identity path that cloud restore must never commit, even if an archive carries it. + /// Device-identity path that no restore may commit even if an archive carries it. private const string DeviceUuidPath = "config/device-uuid.json"; private readonly string _dataDirectory = Utils.DataRoot; @@ -103,65 +87,6 @@ public Task ExportAllDataAsync(string destinationPath, CancellationToken return Task.Run(() => CreateArchive(destinationPath, ArchiveKind.AllData, AllDataRoots, cancellationToken), cancellationToken); } - /// - /// Resolves the cloud archive root set from the dedicated cloud backup-content selection. - /// stays the hard ceiling, so the device identity, the voice - /// cache, and logs are never uploaded even when the local backup includes them. - /// - public static IReadOnlyList ResolveCloudBackupRoots(BackupConfig backup) - { - ArgumentNullException.ThrowIfNull(backup); - var selection = new HashSet(StringComparer.OrdinalIgnoreCase); - if (backup.CloudIncludeConfig) selection.Add("config/settings.json"); - // 全屏渠道的文案库跟着「配置」一起上云:它是一份小的文本清单,属于通知与外观配置的一部分, - // 而且没为它单开一行勾选——单开一行会把云备份内容选择从 7 行变成 8 行,属于另一件事。 - if (backup.CloudIncludeConfig) selection.Add("texts"); - if (backup.CloudIncludeList) selection.Add("list"); - if (backup.CloudIncludeHistory) selection.Add("history"); - if (backup.CloudIncludeAudio) selection.Add("audio"); - if (backup.CloudIncludeCses) selection.Add("CSES"); - if (backup.CloudIncludeImages) selection.Add("images"); - if (backup.CloudIncludeProofs) selection.Add("proofs"); - - return CloudBackupRoots - .Where(root => AlwaysSelectedCloudRoots.Contains(root, StringComparer.OrdinalIgnoreCase) - || selection.Contains(root) - || selection.Any(chosen => root.StartsWith(chosen + "/", StringComparison.OrdinalIgnoreCase))) - .ToArray(); - } - - /// The cloud root set the current cloud backup-content selection resolves to. - public IReadOnlyList GetCloudBackupRoots() => ResolveCloudBackupRoots(configHandler.Data.General.Backup); - - /// - /// Creates the account cloud-sync package from the cloud backup-content selection. The archive - /// is a normal v3 archive with , and its root set is - /// capped by , so an upload never carries plugins, the voice - /// cache, the device identity, credentials, or logs. - /// - public Task ExportCloudBackupAsync(string destinationPath, CancellationToken cancellationToken = default) - { - var roots = GetCloudBackupRoots(); - return Task.Run(() => CreateArchive(destinationPath, ArchiveKind.CloudBackup, roots, cancellationToken), cancellationToken); - } - - /// - /// Read-only inspection for a downloaded cloud backup. A valid v3 archive of any other kind is - /// reported as unsupported instead of being silently restore-equivalent to a cloud package. - /// - public Task InspectCloudBackupAsync(string sourcePath, CancellationToken cancellationToken = default) - { - return Task.Run(() => - { - var inspection = InspectArchive(sourcePath, cancellationToken); - return inspection.Kind == ArchiveKind.CloudBackup - ? inspection - : new ImportInspection(ArchiveFormat.Unknown, inspection.Kind, inspection.ProducerVersion, - inspection.FileCount, inspection.UncompressedBytes, [], - ["该文件不是云端备份归档。"]); - }, cancellationToken); - } - public Task InspectSettingsAsync(string sourcePath, CancellationToken cancellationToken = default) { return Task.Run(() => InspectSettings(sourcePath, cancellationToken), cancellationToken); @@ -213,17 +138,6 @@ public Task ImportAllDataAsync(string sourcePath, CancellationToke return Task.Run(() => ImportArchive(sourcePath, createSnapshot: true, cancellationToken), cancellationToken); } - /// - /// Restores a downloaded cloud backup. Only archives are - /// accepted, and the device identity is filtered out of the commit roots even when a crafted - /// archive contains it, so a cloud restore can never overwrite this device's identity. - /// - public Task ImportCloudBackupAsync(string sourcePath, CancellationToken cancellationToken = default) - { - return Task.Run(() => ImportArchive(sourcePath, createSnapshot: true, cancellationToken, - requiredKind: ArchiveKind.CloudBackup, excludeDeviceIdentity: true), cancellationToken); - } - public string CreateManualBackup(IReadOnlyCollection roots) { if (roots.Count == 0) @@ -261,8 +175,7 @@ public Task RestoreBackupAsync(string sourcePath, CancellationToke return Task.Run(() => ImportArchive(sourcePath, createSnapshot: true, cancellationToken), cancellationToken); } - private ImportResult ImportArchive(string sourcePath, bool createSnapshot, CancellationToken cancellationToken, - ArchiveKind? requiredKind = null, bool excludeDeviceIdentity = false) + private ImportResult ImportArchive(string sourcePath, bool createSnapshot, CancellationToken cancellationToken) { lock (_archiveOperationLock) { @@ -272,10 +185,10 @@ private ImportResult ImportArchive(string sourcePath, bool createSnapshot, Cance var inspection = InspectArchive(sourceCopy, cancellationToken); if (inspection.Kind == ArchiveKind.Diagnostic) throw new InvalidDataException("诊断数据不能导入。"); + if (inspection.Kind == ArchiveKind.CloudBackup) + throw new InvalidDataException("云端备份已停止支持,该归档不能再导入。"); if (!inspection.IsSupportedV3) throw CreateUnsupportedVersionException(inspection); - if (requiredKind is { } kind && inspection.Kind != kind) - throw new InvalidDataException("该文件不是云端备份归档。"); var staging = Path.Combine(_dataDirectory, ".import-staging", Guid.NewGuid().ToString("N")); Directory.CreateDirectory(staging); @@ -295,10 +208,6 @@ private ImportResult ImportArchive(string sourcePath, bool createSnapshot, Cance var rootsToCommit = inspection.Kind == ArchiveKind.AllData ? AllDataRoots : inspection.Roots; - if (excludeDeviceIdentity) - rootsToCommit = rootsToCommit - .Where(root => !root.Equals(DeviceUuidPath, StringComparison.OrdinalIgnoreCase)) - .ToArray(); CommitCandidate(staging, rootsToCommit, inspection.Kind == ArchiveKind.AllData, warnings); ReloadCoreRuntimeState(); warnings.AddRange(postImportHooks.OnAllDataImported()); diff --git a/SecRandom.Core/Services/ControlNode/ControlSettingsLabels.cs b/SecRandom.Core/Services/ControlNode/ControlSettingsLabels.cs index d9a905305..c3e1ca372 100644 --- a/SecRandom.Core/Services/ControlNode/ControlSettingsLabels.cs +++ b/SecRandom.Core/Services/ControlNode/ControlSettingsLabels.cs @@ -147,11 +147,11 @@ private static readonly (string Key, CultureInfo[] Fallback)[] PublishedLanguage // 抽奖的"抽取方式"是按奖盘还是按剩余数量,与点名页的随机/公平不是同一件事。 ["lottery.draw_type"] = R(Picking, "S_LotteryDrawType"), - // 三个抽取页各有自己的"默认记录组"行(点名/抽奖是选择器初始值,闪抽是唯一的选择器)。 - ["roll_call.history_group"] = R(Picking, "S_RollCallHistoryGroup"), - ["quick_draw.history_group"] = R(Picking, "S_QuickDrawHistoryGroup"), - ["lottery.history_group"] = R(Picking, "S_LotteryHistoryGroup"), - + // 三个抽取页各有自己的"默认记录组"行(点名/抽奖是选择器初始值,闪抽是唯一的选择器)。 + ["roll_call.history_group"] = R(Picking, "S_RollCallHistoryGroup"), + ["quick_draw.history_group"] = R(Picking, "S_QuickDrawHistoryGroup"), + ["lottery.history_group"] = R(Picking, "S_LotteryHistoryGroup"), + // 通知类目只暴露渠道开关与显示时长,四个渠道各有一套文案。 ["notification.default.enabled"] = R(Notification, "S_Default_Enabled"), ["notification.roll_call.enabled"] = R(Notification, "S_RollCall_Enabled"), @@ -241,14 +241,10 @@ private static readonly (string Key, CultureInfo[] Fallback)[] PublishedLanguage ["sentry_telemetry_enabled"] = R(Privacy, "S_SentryTelemetry_Enabled"), ["online_status_mode"] = R(Privacy, "S_OnlineStatus_Mode"), - // ---------------- 通用:备份(本地与云端两套内容选择共用同一批文案) + // ---------------- 通用:备份 ["auto_backup_enabled"] = R(Backup, "S_AutoBackup"), ["auto_backup_interval_days"] = R(Backup, "S_AutoBackup_IntervalDays"), ["auto_backup_max_count"] = R(Backup, "S_AutoBackup_MaxCount"), - ["cloud_device_alias"] = R(Backup, "S_CloudDeviceAlias"), - ["cloud_auto_backup_enabled"] = R(Backup, "S_CloudAutoBackup"), - ["cloud_auto_backup_interval_days"] = R(Backup, "S_CloudAutoBackup_IntervalDays"), - ["cloud_auto_backup_max_count"] = R(Backup, "S_CloudAutoBackup_MaxCount"), ["include_config"] = R(Backup, "S_Includes_Config"), ["include_list"] = R(Backup, "S_Includes_List"), ["include_history"] = R(Backup, "S_Includes_History"), @@ -415,8 +411,8 @@ private static readonly (string Key, CultureInfo[] Fallback)[] PublishedLanguage // ---------------- 悬浮窗 ["startup_display_floating_window"] = R(FloatingWindow, "S_Display_StartupDisplay"), - ["show_on_both_sides"] = R(FloatingWindow, "S_Display_ShowOnBothSides"), - ["sync_both_sides_anchor"] = R(FloatingWindow, "S_Display_SyncBothSidesAnchor"), + ["show_on_both_sides"] = R(FloatingWindow, "S_Display_ShowOnBothSides"), + ["sync_both_sides_anchor"] = R(FloatingWindow, "S_Display_SyncBothSidesAnchor"), ["floating_window_opacity"] = R(FloatingWindow, "S_Display_Opacity"), ["floating_window_topmost_mode"] = R(FloatingWindow, "S_Display_TopmostMode"), ["show_roll_call_button"] = R(FloatingWindow, "S_Buttons_RollCall"), @@ -437,6 +433,9 @@ private static readonly (string Key, CultureInfo[] Fallback)[] PublishedLanguage ["stick_to_edge"] = R(FloatingWindow, "S_Interaction_StickToEdge"), ["stick_to_edge_recover_seconds"] = R(FloatingWindow, "S_Interaction_StickToEdgeRecoverSeconds"), ["stick_to_edge_display_style"] = R(FloatingWindow, "S_Interaction_StickToEdgeDisplayStyle"), + ["stick_to_edge_display_text"] = R(FloatingWindow, "S_Dock_Text", FloatingWindow, "S_Dock_Text_D"), + ["stick_to_edge_display_icon_glyph"] = R(FloatingWindow, "S_Dock_Icon", FloatingWindow, "S_Dock_Icon_D"), + ["stick_to_edge_display_icon_image"] = R(FloatingWindow, "S_Dock_Icon", FloatingWindow, "S_Dock_Icon_D"), ["docked_window_size"] = R(FloatingWindow, "S_Dock_Size"), ["draggable"] = R(FloatingWindow, "S_Interaction_Draggable"), ["long_press_duration"] = R(FloatingWindow, "S_Interaction_LongPressDuration"), diff --git a/SecRandom.Shared/Models/Verification/DrawProof.cs b/SecRandom.Shared/Models/Verification/DrawProof.cs index efb970ba8..a67411064 100644 --- a/SecRandom.Shared/Models/Verification/DrawProof.cs +++ b/SecRandom.Shared/Models/Verification/DrawProof.cs @@ -46,36 +46,10 @@ public sealed record class DrawProof [JsonPropertyName("result")] public DrawProofResult Result { get; init; } = new(); - // Local append-only evidence chain. Absent on proofs written before the chain existed (and on - // proofs whose chain could not be advanced); such files are reported as "unchained" instead of broken. - [JsonPropertyName("chain")] - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - public DrawProofChain? Chain { get; init; } - [JsonPropertyName("witness")] public DrawProofWitness? Witness { get; init; } } -/// -/// Position of one proof inside the local append-only chain. Deleting or rewriting a chained proof -/// becomes visible because the surrounding files still link to its hash. -/// -public sealed class DrawProofChain -{ - [JsonPropertyName("formatVersion")] - public int FormatVersion { get; init; } = 1; - - [JsonPropertyName("index")] - public long Index { get; init; } - - [JsonPropertyName("prevHash")] - public string PrevHash { get; init; } = string.Empty; - - // Hash over (index, prevHash, canonical proof hash). It excludes itself, so it cannot be self-referential. - [JsonPropertyName("selfHash")] - public string SelfHash { get; init; } = string.Empty; -} - public sealed class DrawProofResult { [JsonPropertyName("winnerRecordIds")] diff --git a/SecRandom/AGENTS.md b/SecRandom/AGENTS.md index 04f36e4af..d87aed22b 100644 --- a/SecRandom/AGENTS.md +++ b/SecRandom/AGENTS.md @@ -31,10 +31,10 @@ SecRandom/ │ ├── Desktop/ # TaskBarIconService, GlobalShortcutService │ ├── Feedback/ # Explicit Sentry user-feedback submission and standard diagnostic ZIP attachment │ ├── Announcements/ # Public announcement retrieval from the SECTL Appwrite gateway -│ ├── Auth/ # Desktop SECTL OAuth session, atomic token store + refresh policy, active-device heartbeat, personal cloud storage client, and the browser page that answers the loopback redirect +│ ├── Auth/ # Desktop SECTL OAuth session, atomic token store + refresh policy, active-device heartbeat, and the browser page that answers the loopback redirect │ ├── Platform/ # App-side neutral window-handle adapter for platform feature requests │ ├── Draw/ # DrawAudioService, DrawTemporaryRecordService -│ ├── ImportExport/ # Desktop shell + post-import hooks over Core Archive services; diagnostics export; account cloud backup orchestration +│ ├── ImportExport/ # Desktop shell + post-import hooks over Core Archive services; diagnostics export │ ├── Linkage/ # CSES/ClassIsland sources, course state runtime, draw authorization, pre-class reset │ ├── Music/ # Managed local draw-music library and stable track selection resolution │ ├── Notification/ # ClassIsland SecRandom4Ci notification bridge @@ -83,12 +83,11 @@ SecRandom/ | Control-plane node (集控) | `Services/ControlNode/`, `../SecRandom.Core/Services/ControlNode/`, `docs/client-protocol.md`, `Views/SettingsPages/General/ControlPage.axaml(.cs)` | Desktop **and tablet** (`MobilePlatformServiceRoot.UsesDesktopMainView`) `control-v1` node agent — which host runs it is decided only by `AppHostShape.RunsControlNode`. The **console side** of 集控 lives in this same project: `ControlPlaneClient` (`Services/ControlPlane/`) is the control-plane REST client behind the shared `IAuthorizedApiSender` bearer boundary, and its base URL is now configurable instead of a compile-time constant — `IControlPlaneEndpointStore` persists it in `data/config/control-plane/endpoint.json` (deliberately not `settings.json`: every request to that address carries this account's access token, so an importable settings file must not be able to repoint it), `ControlPlaneEndpointPolicy` accepts https or plaintext only to loopback (path prefixes allowed, trailing slash normalized away), the client re-reads the stored address per request so a change needs no restart, and `settings.general.control` always shows that card — the debug page's runtime `IControlPlaneEndpointSettingsGate` switch was deleted together with its Debug-page card, so the 高级连接设置 group (节点通道地址 + 控制面地址) no longer has any visibility switch. That page also carries an always-visible 集控平台 button that opens the effective base URL through `IExternalLauncher` and switches its label to 打开第三方托管集控平台 as soon as a custom address is configured. `ControlNodeHostedService` keeps one outbound `ClientWebSocket` alive through `ControlNodeClient` (1s→60s backoff **with jitter**; `unauthorized` retries after a credential refresh, while `invalid_request`/`node_not_found`/`group_not_found` become `Blocked` and wait for a fix instead of retrying). `ControlCommandDispatcher` declares `node.status.read`, `draw.lock`, `draw.trigger`, `media.play`, `settings.write`, `roster.write` **and the two read capabilities** `settings.read` / `roster.read` — `draw.lock` is desired state (`desired_state` revision convergence) and a `draw.lock` **action** is refused, `node.restart` is deliberately not implemented, and reads arrive as `kind: "query"` commands answering through `command.result.result_payload` (`proof.list` stays unimplemented and therefore undeclared). The three newer capabilities are thin wrappers over the testable Core payload contracts (`ControlCommandPayloads.cs`): `ControlMediaPlayHandler` (voice announce, `show` refused), `ControlSettingsPatchHandler` (whitelist patch, applied on the UI thread through `MainConfigHandler.Save`), `ControlRosterPushHandler` (backup, `replace`/`merge` via `ControlRosterMerge` which updates in place to keep `RecordId`, `activate` switches the active list only on request; student rosters come from `students[]` and prize pools from `roster_kind: "prizes"` + `prizes[]`, both with the tri-state per-member `tags` — omitted means "leave them alone"). The device-owned switch, `node_id`, `group_id`, endpoint and applied revision live in `data/config/control/node-state.json` (never `settings.json`), are written through `IControlNodeStateStore`, and gate every action command. Remote `draw.trigger` runs the shared quick-draw session on the UI thread after `LinkageDrawCoordinator.EvaluateGate` proves no interactive verification would be raised. The settings page is `settings.general.control`. The node **never reports the class/roster name**: `IControlNodeStatusSource` was removed rather than left as an unused seam, so `hello`/`heartbeat` carry no `current_class`. They do carry a **device display name** (`display_name` via `ControlNodeDisplayName.Resolve`): the name configured in `settings.general.control`, falling back to `ControlNodeClientOptions.HostName` (the host name) so the console never shows only a random `node_id`. | | Settings/data import-export | `Services/ImportExport/`, `../SecRandom.Core/Services/Archive/`, `Views/SettingsView.axaml(.cs)` | Core `DataArchiveService` owns strict v3 ZIP/JSON transfer, manifest/SHA-256 validation, manual/automatic backups, staging commit/rollback, and mandatory pre-import snapshots; platform follow-up work goes through `IArchivePostImportHooks` (desktop implementation: runtime refresh + desktop-integration sync). Desktop `IImportExportService` is a thin shell that adds diagnostics export and delegates everything else; diagnostics read `data/logs` and `data/crashes` through `../SecRandom.Core/Helpers/SharedFileReader.cs` and name every unreadable file in `diagnostic/unreadable-logs.txt` instead of skipping it silently; `AutomaticBackupService` is Host-managed and checks configured backup cadence. Draw-verification proof files live under `data/proofs` and are included by default in both manual and automatic backups. The settings shell owns pickers, preview/confirmation, feedback, and restart requests. | | Searchable settings metadata | `Services/Settings/SettingsSearchService.cs` | Reflects `Langs.SettingsPages.*` resources and registered settings pages. Current setting rows use stable `x:Name` IDs; nested targets may be resolved through the visual tree and obsolete resource entries are excluded. | -| Account cloud backup | `Services/ImportExport/CloudBackupService.cs`, `Services/ImportExport/CloudAutomaticBackupService.cs`, `Services/Auth/SectlCloudStorageClient.cs`, `Views/SettingsPages/General/BackupSettingsPage.axaml(.cs)` | Desktop and mobile account cloud sync. `CloudBackupService` packages a `CloudBackup` archive, uploads verified 512 KiB parts plus a trailing manifest, lists/groups cloud backups, verifies a download before restore, deletes parts before the manifest, and purges incomplete backups; `SectlCloudStorageClient` owns the `/api/cloud/*` transport and maps service error codes. `CloudAutomaticBackupService` is the hosted service behind `BackupConfig.CloudAutoBackup*`: it uploads on the configured cadence while signed in and calls `CloudBackupService.UploadAutomaticAsync`, which is the only path allowed to free space. Every upload stamps this device's alias (`BackupConfig.CloudDeviceAlias`, default host name) into the backup id, retention trims only this device's own surplus, and only an exhausted quota still removes the account-wide oldest backup. The backup settings page shows the whole cloud tab whenever `SectlAuthService`/`CloudBackupService` resolve, on desktop and mobile, and never caches cloud state in configuration. Cloud backups carry no client-side encryption and no passphrase: the archive is uploaded as produced, so account access is the only key and any signed-in device can list and restore every backup. A package the removed encryption feature uploaded is still recognised by its `-enc` name marker and stays listed — marked 旧版加密,无法恢复 and never restorable (`CloudBackupService.CanRestore` is false) — so the user can see and delete it, but only an older build could open it. | | ClassIsland notifications | `Services/Notification/`, `../SecRandom4Ci.Interface/` | Sends draw-result DTOs to the optional ClassIsland `SecRandom4Ci` plugin through v2 IPC. | | Profile persistence | `../SecRandom.Core/Services/Profiles/ProfileService.cs`, `../SecRandom.Core/Services/Profiles/ProfileCatalogManager.cs` | Current lists/history, active point-call list/history switching, catalog rename/delete/create, and `SaveProfile()`; list items carry hidden `RecordId` identity. | | Roster transfer | `Services/RosterTransfer/`, `Views/SettingsPages/ListManagement/` | Offline QR export pre-generates all manifest/data PNG frames in memory, then loops them. Quick QR and session-code export encrypt the `.xlsx`/`.csv` archive locally with AES-256-GCM and send only its ciphertext to SecRandom Sync; quick QR keeps the random key in the URL fragment, while session mode sends only a SHA-256 code hash. The cloud payload limit is 1 MiB and the offline QR limit is 300 KiB. List-management drawers expose file, quick-QR, offline-QR, and session-code sources; show the three-row preview only after a source has validated, and auto-validate a complete 12-character session code. The settings menu provides these four transport choices only for settings; full-data import/export remains a direct local ZIP operation. Both importers resolve `IRosterQrCameraCaptureFactory` from Host and use its one in-memory frame, permission, error, and disposal workflow. Their `RosterQrCameraPreview` is provider-neutral. On Windows, named DirectShow devices (including OBS virtual cameras) open through OpenCV; Linux derives V4L2 names and indexes, macOS derives AVFoundation names and indexes, and Android surfaces Camera2 device IDs through CameraView facing. The selector is shown only when more than one device is available; iOS keeps default-camera QR scanning and hides it. Every export-drawer close path revokes the active cloud transfer, including a close racing an in-flight upload; every import-drawer close path cancels session-code work, disposes the camera, and deletes the local copy it made for a storage file without a path. Never offer QR-image file selection or persist roster transfer frames. The CameraView Android backend does persist one full-resolution JPEG per shutter release under the app's external files directory and never deletes it, so the QR scan session reclaims those files through the head-injected `IMobileCameraCaptureStore` (`MobilePlatformServiceRoot.CameraCaptureStore`; the Android head implements it with `RosterQrCaptureFiles`, iOS keeps the no-op default because it composes every frame in memory): a session clears leftovers when it starts, after every photo fallback capture, and on disposal (the session-boundary sweeps skip captures younger than five seconds so a sweep cannot delete a file another session's backend still has to read), and the mobile startup path clears everything once in the background, isolated from the startup failure path. The photo fallback itself is capped at three attempts per session, because preview frames stay the primary frame source. Spreadsheet imports pick their range through the shared `RosterImportRegionSelector` (`Views/SettingsPages/ListManagement/`), which owns the worksheet/header-row/data-row controls and the clickable raw row preview; the drawers keep the raw grid from `MiniExcel.Query(..., useHeaderRow: false)`, rebuild column mapping + preview on every region change, and re-read the file by worksheet name because the selector never touches the file system itself. Its row numbers are raw spreadsheet rows (MiniExcel pads missing rows), so they match Excel. `GetSheetNames` is skipped for CSV, which is not a zip package and throws there. | | Voice announcements | `Services/Voice/`, `Controls/AttachedSettings/SpecificAnnouncementAttachedSettingsControl.axaml(.cs)` | App-layer TTS runtime: `ISpeechProvider` implementations enumerate/synthesize system, Edge, or OmniTTS audio; `SpeechAudioPlayer` owns SoundFlow/MiniAudio playback; `VoiceAnnouncementService` builds one batched result announcement and can pre-generate the audio cache in bulk. `OmniTtsSpeechProvider` (engine 2) aggregates OpenAI/FishAudio/MiMo/Custom providers with API-fetched or manually typed models and voices; `OmniTtsCredentialStore` keeps keys in `data/config/voice/omnitts-keys.json`; `MiMoVoiceReferenceStore` keeps authorized WAV clone references privately under `data/config/voice/`. The registered `专属语音` attached setting supplies per-student/per-prize alias, prefix, and suffix. | -| Draw-proof attestation | `Services/Verification/` | `DrawProofExportService` chains each proof (`ProofChainStore`, `data/proofs/chain-head.json`) and saves it; `DrawProofAttestationService` submits the proof captured at draw time (never a re-read of the file) to `fair.sectl.cn` and optionally to an RFC 3161 authority, retries with bounded backoff, persists `data/proofs/attestation-queue.json`, and reports pending/failed/conflicted items to the verification settings page; `ProofIntegrityVerifier` rebuilds and reports the local chain. | +| Draw-proof attestation | `Services/Verification/` | `DrawProofExportService` cleans up and saves each `OfflineReproducible` proof under `data/proofs`; `DrawProofAttestationService` submits the proof captured at draw time (never a re-read of the file) to `fair.sectl.cn` and optionally to an RFC 3161 authority, retries with bounded backoff, persists `data/proofs/attestation-queue.json`, and reports pending/failed/conflicted items to the verification settings page. Proofs are no longer chained locally: `ProofChainStore`, `ProofIntegrityVerifier`, and the verification page chain check were removed, and a proof without chain fields is still accepted by the service side as an unchained proof. | | Draw audio / temp records | `Services/Draw/DrawAudioService.cs`, `../SecRandom.Core/Services/Draw/DrawTemporaryRecordService.cs` | Audio stays app-layer; session-scoped temporary records are shared Core runtime behavior. | | Managed music library | `Services/Music/MusicLibraryService.cs`, `Views/SettingsPages/Personalized/MusicSettingsPage.axaml(.cs)` | Imports, removes, and previews managed MP3/WAV/FLAC files under `data/audio/music`. | | Desktop integration | `Services/Desktop/` | Taskbar lifecycle, Windows native global shortcuts, cross-platform autostart, and `secrandom://` registration. | @@ -101,9 +100,9 @@ SecRandom/ | Statistics reporting entrance | `SecRandom.Core/Services/Stats/PlatformStatsApi.cs` | Every SECTL statistics report (online status, usage increment, version, last-value field) is posted to this one aggregate entrance `PlatformStatsApi.ReportUri`; never build a per-type URL in the app layer. The service judges the type from the payload keys, so add no field of an earlier rule's shape. | | Online status reporting | `Services/OnlineStatusService.cs` | Host-managed SECTL online status reporter; reads `PrivacySettings.OnlineStatusMode` and posts plain `platform_id`/`device_uuid` (plus version/country) to the aggregate entrance — carrying no `field_key`, `value`, `delta`, or `version`, which would be booked as another figure. | | Version usage reporting | `Services/PlatformVersionReportService.cs` | Host-managed SECTL version-usage reporter: one request per start carrying the build version and the device UUID only — never the SECTL account id — posted to the aggregate entrance (where `version` is what makes it a version report), run off the startup thread, and deliberately not gated by the online-status privacy switch. | -| SECTL OAuth session | `Services/Auth/` | Desktop and mobile account sign-in/token refresh plus a Host-managed logged-in-device heartbeat every five minutes. A mobile head receives the OAuth redirect through the app's custom scheme (`MobileAuthCallbackRouter`: Android intent filter, iOS `ASWebAuthenticationSession`), records its PKCE attempt in `data/config/sectl-auth-pending.json` before the browser opens, and exchanges a redirect that arrives after the process was reclaimed instead of asking the user to authorize again. `SectlTokenStore` owns `data/config/sectl-auth.json` (atomic temp+fsync+rename writes, plus the `sectl-auth.lock` cross-process refresh lock) and `SectlAuthService` owns the refresh policy: the refresh token is single-use, so a rotation is persisted before the new access token is used, concurrent refreshes collapse into one single-flight task, a terminal `400`/`401` clears the local pair (`RequiresReauthorization` + `StateChanged`) instead of looping on the dead token, `429`/`503` back off and retry the same refresh, and an unknown network outcome re-reads the file before retrying. `SectlAuthService.SendAuthorizedAsync` is the shared bearer-and-single-refresh boundary for other SECTL APIs; `SectlCloudStorageClient` exposes the personal cloud storage API on top of it. `SectlAuthService.InitializeAsync` only reads the local token and raises `StateChanged`; the `/api/oauth/userinfo` profile and avatar download run in the background, because `App.StartRuntimeServicesAsync` awaits it before `Host.StartAsync()` and the settings window awaits that startup task — awaiting account network calls there makes a slow SECTL API stall settings navigation. The `/api/oauth/token` and `/api/oauth/refresh` payloads carry the grant fields plus the device UUID only: the client must not resolve its own public IP (no third-party IP lookup call) nor upload an `ip_address`, because the service derives the address from the connection. | +| SECTL OAuth session | `Services/Auth/` | Desktop and mobile account sign-in/token refresh plus a Host-managed logged-in-device heartbeat every five minutes. A mobile head receives the OAuth redirect through the app's custom scheme (`MobileAuthCallbackRouter`: Android intent filter, iOS `ASWebAuthenticationSession`), records its PKCE attempt in `data/config/sectl-auth-pending.json` before the browser opens, and exchanges a redirect that arrives after the process was reclaimed instead of asking the user to authorize again. `SectlTokenStore` owns `data/config/sectl-auth.json` (atomic temp+fsync+rename writes, plus the `sectl-auth.lock` cross-process refresh lock) and `SectlAuthService` owns the refresh policy: the refresh token is single-use, so a rotation is persisted before the new access token is used, concurrent refreshes collapse into one single-flight task, a terminal `400`/`401` clears the local pair (`RequiresReauthorization` + `StateChanged`) instead of looping on the dead token, `429`/`503` back off and retry the same refresh, and an unknown network outcome re-reads the file before retrying. `SectlAuthService.SendAuthorizedAsync` is the shared bearer-and-single-refresh boundary for other SECTL APIs. `SectlAuthService.InitializeAsync` only reads the local token and raises `StateChanged`; the `/api/oauth/userinfo` profile and avatar download run in the background, because `App.StartRuntimeServicesAsync` awaits it before `Host.StartAsync()` and the settings window awaits that startup task — awaiting account network calls there makes a slow SECTL API stall settings navigation. The `/api/oauth/token` and `/api/oauth/refresh` payloads carry the grant fields plus the device UUID only: the client must not resolve its own public IP (no third-party IP lookup call) nor upload an `ip_address`, because the service derives the address from the connection. | | Update center | `Services/Updates/`, `Views/SettingsPages/Update/` | Desktop `UpdateSettingsPage` is the shared `settings.update` surface for desktop and mobile, backed by signed full-artifact checks, portable staging/Launcher restart, or native installer handoff. | -| Security authorization | `Services/Security/` | `SecuritySettingsStore` owns the security settings in `data/config/security/settings.json` (AES-256-GCM envelope plus a device-local `settings.key`, with maximal-protection fail-closed defaults when that file cannot be read), alongside separate credential storage, password/TOTP/USB factors, removable-device catalog, lockout state, operation authorization gateway, the opt-in settings-file integrity fingerprint (`SettingsIntegrityService`), and its backup-based automatic recovery (`SettingsIntegrityRecoveryService`, used only by the desktop startup gate and registered as a Host singleton). `App` resolves the store right after `BuildHost()` so the protection switches — and the one-time migration out of `settings.json` — exist before the OOBE and integrity gates read them. | +| Security authorization | `Services/Security/` | `SecuritySettingsStore` owns the security settings in `data/config/security/settings.json` (AES-256-GCM envelope plus a device-local `settings.key`, with maximal-protection fail-closed defaults when that file cannot be read), alongside separate credential storage, password/TOTP/USB factors, removable-device catalog, lockout state, and the operation authorization gateway. `App` resolves the store right after `BuildHost()` so the protection switches — and the one-time migration out of `settings.json` — exist before the OOBE reads them. | | URL/IPC automation | `Services/Ipc/ProtocolCommandRouter.cs`, `Core/Services/SingleInstance/` | URL activation and duplex structured IPC share one protected command router; legacy plaintext activation remains supported. | ## CONVENTIONS @@ -125,7 +124,9 @@ SecRandom/ - The timer's desktop mini window is a direct borderless `Window` sharing the Host singleton `TimerViewModel`; its non-button content uses `WindowDecorationProperties.ElementRole="TitleBar"` for native decoration dragging, while icon buttons use `ElementRole="User"` and restore the full MVE view. - `TimerViewModel` owns timer commands and persists its six most recent countdown preset durations through `MainConfigHandler`; `TimerView` only hosts the AXAML and forwards keyboard input. - Timer auto-shrink is **idle-based, not timing-based**: `TimerViewModel.NotifyUserActivity()` (called by `TimerView` on attach, on pointer press/move, and on key input) resets the "no operation for N seconds" clock and re-arms the trigger, and `TimerViewModel` evaluates `TimerSettingsConfig.ShouldShrinkToMiniWindow` for the **currently displayed mode** (countdown on by default, stopwatch and clock off) then raises `AutoMiniWindowRequested`. Because a page that is simply sitting there has no ticking timer and no clock refresh, `UpdateRefreshTimer` must also keep a 1 s tick while the idle watch is armed — otherwise the feature can never fire in the one case it exists for. One stretch of inactivity shrinks at most once, so restoring the full window does not re-shrink until the user touches something. `TimerViewService` owns the switch — it opens the mini window **before** closing the full `main.timer` view, because Avalonia shuts the application down when the last window closes. The switches live on the desktop-only `settings.personalized.timer` page (`TimerSettingsPage`, three mode rows plus the shared delay with quick presets), persist through `MainConfigHandler`, and need no restart; the four `timer.*` paths are also part of the control-plane settings catalog (see `ControlSettingsCatalog`/`ControlSettingsLabels`), so a change there applies from the next stretch of inactivity on. -- `MainWindow` and `FloatingWindow` retain their presentation and configuration behavior but request topmost through `IWindowFeatureService`; `FloatingWindow` requests `ToolWindow` during construction while its native handle is available but before its first show, then requests task-switcher exclusion after opening where supported. Its transparent composition hint must be set during construction. Floating-window restoration must preserve `ShowActivated=False` and not steal focus. The user-facing 无焦点模式 (`FloatingWindowSettings.DoNotStealFocus`, default on, live-applied) reuses the same seam: `FloatingWindow` owns one `ApplyFocusFreeMode()` helper that sets `ShowActivated = !DoNotStealFocus` and requests `WindowFeatures.NoActivate`, and it is called from the constructor (while the native handle exists but before the first show), from `OnOpened`, and from `ApplyWindowSettings` — the last one is what makes the setting apply instantly and what covers simple mode and config reloads. Windows implements `NoActivate` as `WS_EX_NOACTIVATE` and applies it without hide/show, so toggling the setting on a visible window must never make the window blink or disappear (the v2 build had exactly that bug; do not reintroduce a hide/show round-trip). Linux and macOS declare no `NoActivate` capability, so they fall back to `ShowActivated=false` alone (show does not steal focus, click still activates) and the settings page hides the row through its `SupportsNoActivate` capability property. The focus-free style only suppresses activation — pointer input keeps working, so the floating window's buttons, custom dragging, and long press are unaffected. Linux implements tool/task-switcher semantics through X11 EWMH when `DISPLAY` is available, including XWayland sessions; native Wayland remains out of scope. macOS maps `ToolWindow` to an `NSWindow` utility window that joins all Spaces; Command-Tab remains application-level and is not modeled as a per-window task-switcher exclusion. 左右两侧同时显示开启时,`FloatingWindow` 用 `isSecondary` 区分角色:主窗钉右、副窗钉左(`SetEdgePinned`),关掉开关后保留右侧主窗,此后拖动只改纵向位置;副窗 `SavePosition` 只写 `FloatingWindowSettings.SecondaryAnchorCenterY`,不碰共享的 `FloatPosition`。两侧高度统一(`FloatingWindowSettings.SyncBothSidesAnchor`,默认开启,只在左右两侧同时显示开启时才在设置页显示)复用同一个锚点:`App.AlignFloatingWindowAnchors()` 在布置或开关切换后把一侧的锚点压给另一侧,拖动过程中由 `App.SyncFloatingWindowAnchor()` 调 `FloatingWindow.ApplyUnifiedAnchor()` 实时跟随;关闭后两侧各自记住自己的高度。 +- `MainWindow` and `FloatingWindow` retain their presentation and configuration behavior but request topmost through `IWindowFeatureService`; `FloatingWindow` requests `ToolWindow` during construction while its native handle is available but before its first show, then requests task-switcher exclusion after opening where supported. Its transparent composition hint must be set during construction. Floating-window restoration must preserve `ShowActivated=False` and not steal focus. The user-facing 无焦点模式 (`FloatingWindowSettings.DoNotStealFocus`, default on, live-applied) reuses the same seam: `FloatingWindow` owns one `ApplyFocusFreeMode()` helper that sets `ShowActivated = !DoNotStealFocus` and requests `WindowFeatures.NoActivate`, and it is called from the constructor (while the native handle exists but before the first show), from `OnOpened`, and from `ApplyWindowSettings` — the last one is what makes the setting apply instantly and what covers simple mode and config reloads. Windows implements `NoActivate` as `WS_EX_NOACTIVATE` and applies it without hide/show, so toggling the setting on a visible window must never make the window blink or disappear (the v2 build had exactly that bug; do not reintroduce a hide/show round-trip). Linux and macOS declare no `NoActivate` capability, so they fall back to `ShowActivated=false` alone (show does not steal focus, click still activates) and the settings page hides the row through its `SupportsNoActivate` capability property. The focus-free style only suppresses activation — pointer input keeps working, so the floating window's buttons, custom dragging, and long press are unaffected. Linux implements tool/task-switcher semantics through X11 EWMH when `DISPLAY` is available, including XWayland sessions; native Wayland remains out of scope. macOS maps `ToolWindow` to an `NSWindow` utility window that joins all Spaces; Command-Tab remains application-level and is not modeled as a per-window task-switcher exclusion. 左右两侧同时显示开启时,`FloatingWindow` 用 `isSecondary` 区分角色:主窗留在它原本那一侧、副窗钉在另一侧(`SetEdgePinned`,主窗在哪侧由 `FloatingWindow.IsOnLeftSide` 判定),关掉开关后保留原来那一侧的主窗(原本在左就回左边、原本在右就留在右边),此后拖动只改纵向位置;副窗 `SavePosition` 只写 `FloatingWindowSettings.SecondaryAnchorCenterY`,不碰共享的 `FloatPosition`。两侧高度统一(`FloatingWindowSettings.SyncBothSidesAnchor`,默认开启,只在左右两侧同时显示开启时才在设置页显示)复用同一个锚点:`App.AlignFloatingWindowAnchors()` 在布置或开关切换后把一侧的锚点压给另一侧,拖动过程中由 `App.SyncFloatingWindowAnchor()` 调 `FloatingWindow.ApplyUnifiedAnchor()` 实时跟随;关闭后两侧各自记住自己的高度。 +- 通知窗(内置闪抽结果窗)的自适应前景色走"一次性桌面采样 + 并行建窗":`App.PrepareQuickDrawNotificationWindowAsync` 是唯一入口,它先用 `TryResolveQuickDrawNotificationTargetRect` 预测目标矩形、在后台启动 `ResolveQuickDrawNotificationThemeAsync`,窗口以 `Opacity=0` 占位显示后再定位、写入主题并淡入(`FadeInQuickDrawWindowAsync` 只 `ObserveTask` 不 await,绝不能把开抽推迟 90ms);采样由 `PlatformStartupContext.Current.ScreenLuminance` 提供,60ms 超时、区域外扩 48px、窗口已可见时剔除自身矩形,`null`/像素数不足/异常一律回退 `AdaptiveBackdropResolver.FromAppTheme`。结果项文字色取 `AdaptiveTheme.Foreground`(强调色只留给边框,对比度不可让位),`QuickDrawPage.ApplyNotificationTheme` 通过整体替换 `RootBorder.Resources` 覆盖 Fluent 色键,`NotificationTheme` 为 `null` 时恢复主题画刷。**不要**把这里改成每帧或每秒截图,也不要在 `ShowNotificationPreview` 之后才写主题(结果项已按旧前景构造)。左右两侧浮窗不做截图自适应:构造期按 `App.IsAcrylicBlurSupported && UiMotion.UseWindowCompositionEffects && !UiRenderQuality.IsLowSpecMode` 请求 `AcrylicBlur`(否则仍 `Transparent`),acrylic 下不透明度由 `WindowBorder` 的 tint alpha(0.78–0.95)承载且 `WindowBorder.Opacity=1`,非 acrylic 保持原来的 `Border.Opacity` 行为,主题变体切换时重算 tint。 + 这条能力的用户开关是 `NotificationSettings.Default.AdaptiveForeground`(默认 `true`,旧 settings.json 缺键即按开处理),只出现在 `settings.notification.floatingWindow` 页(`NotificationFloatingWindowSettingsPage`)。低配模式(`UiRenderQuality.IsLowSpecMode`)下该页把开关置灰并显示为关,但**不改写用户偏好**,退出低配后自动恢复;`App.ResolveQuickDrawNotificationThemeAsync` 用 `!settings.AdaptiveForeground || UiRenderQuality.IsLowSpecMode` 走同一条回退,所以关掉开关也不会再多抓一次屏。同类"被全局条件压成空操作"的开关一律按这个规则处理(置灰 + 显示实际生效值 + 不覆盖偏好):目前只有全屏通知页的「动画样式」(低配固定 `Direct`)与「背景模糊」(低配不渲染、显示 0),见 `FullscreenNotificationSettingsPage` 的 `IsLowSpecModeActive`/`BackgroundBlurRadius`。抽取动画只降帧(`AnimationFramePolicy`)不禁用,因此那里的开关保持可用。 - `App` is shared by desktop and mobile. Its SingleView branch initializes only `MobileViewHost`, `MobileRootView`, mobile routes/media/update/status services, and the `SingleViewHostProvider`; it must not route through desktop single-instance, OOBE, floating-window, tray, shortcut, update scheduler, or protocol startup paths. - Mobile code belongs to this project: `Mobile/` owns neutral platform contracts and lifecycle support, while `BuildHost()` owns mobile composition. `Views/Mobile/`, `Controls/Mobile/`, `Services/Mobile/`, and `Langs/Mobile/` own their corresponding @@ -146,12 +147,11 @@ SecRandom/ - The desktop loopback redirect is answered with `LoopbackAuthCallbackPage`, one self-contained document (inline CSS, inline app icon, no script, no second request) rather than a bare `

`. Its wording must never claim a finished sign-in: `SectlAuthService` writes and closes that response *before* it validates `state` and exchanges the code, so the page can only say "back in SecRandom". `LoopbackAuthRedirectBroker` keeps answering requests that carry neither `code` nor `error` (a browser asking for `/favicon.ico`) instead of spending its one read on them, and a browser that closes the tab mid-write must not turn an already-received callback into a failure. Responses carry `default-src 'none'` CSP, `no-store`, and `nosniff`, and the page must stay usable without JavaScript — a background tab may never render it. - `SectlHeartbeatService` runs on desktop and mobile and is independent of `OnlineStatusService` and its privacy mode: while an OAuth session is signed in, it immediately reports after startup/sign-in and then calls `/api/oauth/heartbeat` every five minutes with the current Bearer token. The authentication service refreshes a rejected access token once before retrying (and proactively five minutes before the stored expiry), and a heartbeat response body is irrelevant: `devices_updated: 0` is a normal answer, not a failure. Heartbeat failures must remain background-only. - SECTL OAuth tokens never expire by time, so the client must not end a session by age: the service keeps both TTLs at `-1`, reports `expires_in = 315360000` as a ten-year placeholder, and introspection returns `expires_at: "-1"` with `exp: null`. `SectlAuthService.ResolveAccessTokenLifetime` maps a negative/absent lifetime to `UnlimitedExpiresInSeconds`, and only revocation ends a session. `InitializeAsync` verifies the stored pair in the background through `POST /api/oauth/introspect` (`token` + `client_id`) and reports the answer as `SectlTokenIntrospection`: `active: false` clears the local pair and requires re-authorization, while any failure (unreachable endpoint, non-success status, bad body) keeps the session, because a flaky network must never be mistaken for a revoked one. Never parse that `"-1"` as a date — it reads as 2000-12-31 and would throw a fresh session away. -- Account cloud backup runs on desktop and mobile and is separate from the anonymous SecRandom Sync channel: roster/settings quick transfer keeps its AES-256-GCM envelope and 1 MiB cap, while cloud backups use the authenticated `/api/cloud/*` API with the signed-in account. `CloudBackupService` registers for desktop and mobile in `BuildHost()`; the backup settings page resolves it with `TryGetService` and hides the whole cloud tab only when it or `SectlAuthService` is missing, so an unsupported host never shows a non-functional section. Cloud parts are uploaded before the trailing manifest, downloads must pass per-part and whole-archive SHA-256 verification before the mandatory recovery snapshot and staging commit, and cloud state is always rediscovered by listing rather than persisted in configuration. Cloud backup encryption and its passphrase were removed on purpose: the archive is uploaded exactly as `ExportCloudBackupAsync` produced it, so account access is the only key and any signed-in device can list and restore any backup — the platform can read a cloud backup, which is the accepted trade-off for recoverability. A package the removed feature uploaded is still recognised by the `-enc` file-name marker, so the list labels it 旧版加密,无法恢复 without a manifest download and `CloudBackupService.CanRestore` is false for it; its schema-2 manifest also fails `ValidateManifest`, because this build holds no way to derive its key. Cloud backup content has its own selection (`BackupConfig.CloudInclude*`) that `DataArchiveService.ResolveCloudBackupRoots` maps onto the fixed `CloudBackupRoots` ceiling, so what the user unchecks is dropped while the device identity, the voice cache, theme resources, logs, plugins, and credentials can never be uploaded (the cloud content list deliberately has no row for them); draw proofs do have a row (`BackupConfig.CloudIncludeProofs`, default off) because a cloud copy is the last resort once the local chain has been deleted; `IImportExportService.GetCloudBackupRoots` feeds that same resolved set into the cloud manifest. The page auto-fetches the quota on entry, after a sign-in state change, and when `CloudBackupService.AutomaticBackupUploaded` fires, because an automatic upload also frees space; it must still never cache cloud state in configuration. Automatic cloud backup is its own opt-in setting set (`BackupConfig.CloudAutoBackupEnabled`/`IntervalDays`/`MaxCount`, independent of the local `AutoBackup*` values) served by `CloudAutomaticBackupService`, which follows this device's own newest upload for its cadence; only its `CloudBackupService.UploadAutomaticAsync` path may free account space. A device alias (`BackupConfig.CloudDeviceAlias`, empty means the host name, normalized by `CloudBackupPackage.BuildDeviceTag`) is appended to the backup id, so the cloud list shows which machine uploaded a backup without downloading its manifest and retention stays per device — an exhausted quota is the one account-wide deletion (the oldest backup of the whole account), while the retention limit only drops this device's own surplus and never an unattributable backup such as one uploaded before aliases existed. The manual upload path must never delete anything implicitly. -- `UpdateCenterService` is the only update transaction entry point. It must verify raw manifest bytes with the embedded Ed25519 key and verify artifact length/SHA-512 before a complete ZIP deployment or native installer handoff; `UpdateScheduler` only checks and never downloads in the background. Desktop and mobile update checks compare versions through `UpdateVersionComparer`, because release tags are SemVer strings (`v3.0.0-beta.1`) that `Version.TryParse` rejects outright; `MobileUpdateService` reports the installed version from `GlobalConstants.Version` instead of reading an entry assembly, which does not exist on Android. +- `UpdateCenterService` is the only update transaction entry point. It must verify raw manifest bytes with the embedded Ed25519 key and verify artifact length/SHA-512 before a complete ZIP deployment or native installer handoff; `UpdateScheduler` only checks and never downloads in the background. Desktop and mobile update checks compare versions through `UpdateVersionComparer`, because release tags are SemVer strings (`v3.0.0-beta.1`) that `Version.TryParse` rejects outright; `MobileUpdateService` reports the installed version from `GlobalConstants.Version` instead of reading an entry assembly, which does not exist on Android. Update source preference (`UpdateSettingsConfig.UpdateSource`: Auto/Sectl/GitHubMirror/GitHub) is expanded only by `Services/Updates/UpdateSourceResolver`: Auto probes the three concrete sources in parallel for TTFB (GET + headers only, 1.5 s timeout, 10-minute single-flight cache) and orders by latency with unreachable sources last, while a manual choice is tried first and keeps the remaining sources as fallback. Everything below that resolver works with a concrete source only, and choosing the official source must never relax the Ed25519 manifest, SHA-512, tag, or channel checks; the Sectl source reads the tag from `/api/software/latest-tag` and its bytes from the non-counting `/api/software/update-file`, never from `/api/software/download` (which books a download event per request). - Security services are Host singletons. Keep secrets out of normal config and route protected window, tray, draw, and linkage operations through `ISecurityService` instead of duplicating checks in UI event handlers. The password editor's strength readout comes from Core `PasswordStrengthEvaluator` and is advisory; never turn it into a validation gate or re-add password rules in the dialog. - Settings URL/IPC preview navigation uses `NavigateToPreviewPage`; ordinary `NavigateToPage` exits preview and is reserved for authorized editing. Avatar downloads never attach OAuth tokens and accept only the fixed API HTTPS origin. OmniTTS credentials are bound to provider plus normalized API origin; legacy provider-only entries cannot be automatically trusted from settings, origin changes require a separately entered key, remote HTTP is rejected, and the `omnitts` named client disables automatic redirects. - Security credentials live only in `data/config/security/credentials.json`. Its internal `FormatVersion` governs the format; the user's password uses Argon2id to derive the AES-256-GCM key, so the file is portable between supported hosts. Do not add DPAPI, Keychain, `secret-tool`, platform key files, filename version suffixes, or legacy credential-file migration. `SecurityCredentialStore` additionally restricts the whole `data/config/security` directory to the current user (Unix `0700`/`0600`, Windows ACL without inherited rules) because the directory also holds the readable `totp-standalone.json` copy; keep that hardening best-effort, applied once per process and on every save, and never let it make the directory unreadable to the app itself. The protection switches are **not** in `settings.json` either: `SecuritySettingsStore` keeps them in the encrypted sibling `data/config/security/settings.json` (AES-256-GCM plus the device-local `settings.key`), and reading them must never fall back to "protection off" — an undecryptable file, or a missing file while a security password is configured, yields maximal protection plus `IsIntegrityCompromised`. That is what makes a text editor useless against this file; the residual boundary is the same as the credentials file, since anyone who can read the directory can forge it. -- Security settings mutations use `ISecurityService`'s password-gated update boundary once protection is active; pages project their state one-way and must not directly persist factor or protected-operation changes. Every security-page control — factor selection, protection switches, the settings-integrity switches, and the Sudo switch and duration — must call `UpdateSecuritySettingsAsync`, because that boundary is what rejects a protection-loosening change without a fresh password; a direct model write bypasses it (the Sudo duration control previously did, and that has been fixed). Credential-level operations are the exception that proves the rule: removing the password, setting up or removing TOTP, and binding/unbinding USB all need the credential envelope itself, so they go through their own fresh-password `ISecurityService` methods (`RemovePasswordAsync`, `BeginTotpSetupAsync`/`ConfirmTotpAsync`/`RemoveTotpAsync`, `BindUsbAsync`/`UnbindUsbAsync`) instead of `UpdateSecuritySettingsAsync`; `RemoveTotpAsync` clears the seed, deletes the `totp-standalone.json` copy, and discards an unconfirmed pending setup. The TOTP row keeps one command button (`C_SetTotp`/`C_ResetTotp` by `HasTotp`) plus a `C_RemoveTotp` button that is visible only while `HasTotp`. The page reads and saves its model through `SecuritySettingsStore` (never `ViewModel.Config`), because those switches left `settings.json` — and `SettingsIntegrityService` subscribes to that store's `Saved` event so toggling the integrity check still records or clears the `settings.json` fingerprint. The Sudo card stays one expandable `FASettingsExpander` (`S_SudoMode`) whose nested rows carry the `S_SudoMode_Enabled`/`S_SudoMode_Duration` search IDs, because `SettingsSearchService` derives search metadata from resource keys (`S_X` root, `S_X_Y` sub) — renaming a key without the matching view `x:Name` breaks that search jump. `IRemovableStorageCatalog` is implemented by the Windows, Linux, and macOS platform projects (mobile uses an empty catalog); `IUsbDeviceCatalog` exposes only ready program-enumerated volumes, and the USB binding dialog selects its `UsbDeviceInfo` rows (drive letter, disk name, device ID) rather than arbitrary folders or paths. Current mount roots remain inside the catalog/security-service implementation and must not appear in `UsbDeviceInfo`, dialog results, public security APIs, or IPC. `ISecurityService.BindUsbAsync` accepts only the selected device ID and resolves the current mount internally. +- Security settings mutations use `ISecurityService`'s password-gated update boundary once protection is active; pages project their state one-way and must not directly persist factor or protected-operation changes. Every security-page control — factor selection, protection switches, and the Sudo switch and duration — must call `UpdateSecuritySettingsAsync`, because that boundary is what rejects a protection-loosening change without a fresh password; a direct model write bypasses it (the Sudo duration control previously did, and that has been fixed). Credential-level operations are the exception that proves the rule: removing the password, setting up or removing TOTP, and binding/unbinding USB all need the credential envelope itself, so they go through their own fresh-password `ISecurityService` methods (`RemovePasswordAsync`, `BeginTotpSetupAsync`/`ConfirmTotpAsync`/`RemoveTotpAsync`, `BindUsbAsync`/`UnbindUsbAsync`) instead of `UpdateSecuritySettingsAsync`; `RemoveTotpAsync` clears the seed, deletes the `totp-standalone.json` copy, and discards an unconfirmed pending setup. The TOTP row keeps one command button (`C_SetTotp`/`C_ResetTotp` by `HasTotp`) plus a `C_RemoveTotp` button that is visible only while `HasTotp`. The page reads and saves its model through `SecuritySettingsStore` (never `ViewModel.Config`), because those switches left `settings.json`. The Sudo card stays one expandable `FASettingsExpander` (`S_SudoMode`) whose nested rows carry the `S_SudoMode_Enabled`/`S_SudoMode_Duration` search IDs, because `SettingsSearchService` derives search metadata from resource keys (`S_X` root, `S_X_Y` sub) — renaming a key without the matching view `x:Name` breaks that search jump. `IRemovableStorageCatalog` is implemented by the Windows, Linux, and macOS platform projects (mobile uses an empty catalog); `IUsbDeviceCatalog` exposes only ready program-enumerated volumes, and the USB binding dialog selects its `UsbDeviceInfo` rows (drive letter, disk name, device ID) rather than arbitrary folders or paths. Current mount roots remain inside the catalog/security-service implementation and must not appear in `UsbDeviceInfo`, dialog results, public security APIs, or IPC. `ISecurityService.BindUsbAsync` accepts only the selected device ID and resolves the current mount internally. - `ProtocolCommandRouter` is a Host singleton and is the only app-layer URL/IPC command dispatcher. Keep IPC request handling on the UI dispatcher for UI mutations; `data/*` must use `IProfileQueryService` snapshots and never switch an active profile. - Roll-call, lottery, and quick-draw ViewModels are shared draw sessions for UI and IPC. Their protocol methods reuse nonvisual core paths after router authorization; do not resolve a detached transient ViewModel for IPC. List renames from settings and OOBE use the Core catalog manager so list, history, default-selection, and temporary-record file names stay aligned. - The roll-call and lottery pages install FileSystemWatchers on their list directories to refresh dropdowns. A watcher-driven refresh must re-assert the page selection without switching the shared `IProfileService` when the resolved selection equals the pre-refresh value (the ComboBox TwoWay binding writes back a null during the items refresh, which would otherwise hijack the active profile away from another session such as QuickDraw mid-draw); only genuine selection changes — user picks, list deleted/renamed corrections — may call `LoadStudentProfile`/`LoadPrizeProfile`. Draw settings pages own their default-list selector through `DefaultRosterSettingSource` (`Views/SettingsPages/Picking/`): the candidate list (「不使用名单」 first, then the roster files) and the selected index are driven from code instead of a `SelectedItem` binding, because that binding writes a null/empty value back while the items are rebuilt. The source writes only genuine user picks — including the `RosterSelection.None` sentinel, and only while real rosters exist — falls back to the first roster when the stored value is empty and saves it immediately, and it must never persist a null/empty value. QuickDraw must not rely on its `SelectedStudentListName` change event to sync the shared profile: other sessions (e.g. the roll-call page) can legitimately move the shared profile, so `TryLoadDefaultStudentList` explicitly re-loads the resolved default list on every trigger even when its own selection is unchanged. QuickDraw also auto-resets the round's temporary records when the list still has members but no eligible candidates remain (same exhausted-round reset as roll-call/lottery), so a quick draw never stalls on «没有可抽取的成员». Every draw session must re-assert the shared profile to its own selection at the start of its draw (`RollCallPageViewModel`/`LotteryPageViewModel.StartDrawCoreAsync` sync the student list and prize pool before capturing animation candidates), because the shared profile reflects the last user action across pages — a quick draw leaves it on the quick-draw default, so a roll-call draw right after would otherwise animate the wrong page's students while the committed result is corrected only later inside `DrawAsync`. Preview animations run concurrently with the real draw, and the draw commit mutates the temporary records mid-animation; preview frames must use a frozen candidate pool captured **before the draw starts** (roll-call and lottery capture the student candidates in `StartDrawCoreAsync` before creating the draw task, then pass them into `ShowPreviewAsync`) — freezing after the draw starts still races with the commit, so on the last round (pool size == draw count) the frozen pool can already be empty and the animation loses its student info. @@ -161,7 +161,7 @@ SecRandom/ - `IVoiceAnnouncementService` is app-layer because Edge TTS and Windows SAPI are platform/runtime concerns. `ISpeechProvider` separates voice enumeration/synthesis from `ISpeechAudioPlayer`, which owns the ClassIsland SoundFlow/MiniAudio playback package. Edge synthesis comes from the `vendors/EdgeTtsSharp` submodule, whose `Wss` transport is replaced by `Services/Voice/EdgeTtsSharpCompatibility.cs`; that seam only appends a `ConnectionId`, because the endpoint credentials now live in the submodule — `Edge_tts_sharp/EdgeTtsGecToken.cs` mints the `Sec-MS-GEC` v2 token and `EdgeTts.CreateSynthesisUri()` pairs it with `Sec-MS-GEC-Version=2-` on every synthesis (the submodule's old v1 token is refused with `403`, and `EdgeTtsGecToken`'s digest is a deliberately modified SHA-256 that must stay identical to upstream `edge-tts`'s `drm.py`; `SecRandom.Core.Tests/EdgeTtsGecTokenTests.cs` pins its reference vectors and the synthesis address), while generated Edge MP3 and system WAV cache files live under `data/audio/voice` using readable `voice-text` keys; `SpeechRate` is applied by a single SoundFlow player during playback, not synthesis, so pitch remains unchanged. `VoiceSettings.VoiceEnable` is the total announcement switch, while default and per-draw settings determine whether a specific draw type requests an announcement. Per-record TTS alias/prefix/suffix belongs in attached settings on `Student`/`Prize`, not in a standalone settings page. - OmniTTS is voice engine 2 (`OmniTtsSpeechProvider.OmniEngine`) beside System SAPI (0) and Edge TTS (1). `OmniTtsSpeechProvider` implements `ISpeechProvider` and `IOmniTtsCatalog`; its providers (OpenAI, FishAudio, MiMo, Custom OpenAI-compatible) use an OpenAI-compatible REST client plus a native MiMo chat-completions adapter, with model lists fetched from `GET /v1/models` when a key is configured or typed manually — never a fixed list. MiMo voice-design and voice-clone models have dedicated settings rows; clone imports require explicit authorization and WAV input, while the reference remains private and only its hash enters cache identity. `OmniTtsCredentialStore` keeps per-provider API keys in `data/config/voice/omnitts-keys.json` (never in `VoiceSettingsConfig`, settings JSON, IPC, logs, telemetry, backups, or the Android provider). `VoiceAnnouncementService` resolves voice/extension for engine 2 (`.mp3`, or `.wav` for MiMo clone/design and Gemini), falls back to Edge when the OmniTTS key is missing, and exposes bulk cache generation (`GenerateCacheAsync`/`GenerateStudentsCacheAsync`/`GeneratePrizesCacheAsync`, same cache keys as real-time speech) plus `ClearVoiceCache`. The voice settings page registers OmniTTS on all non-iOS platforms (`!OperatingSystem.IsIOS()` stays); its OmniTTS-only rows appear only while `VoiceEngine == 2`. - Verification draws cannot wait for the network. `VerificationDrawCoordinator` must immediately generate and export an `OfflineReproducible` proof, then enqueue it for `DrawProofAttestationService` background retries. The service receipt binds a canonical hash of every proof field except the receipt itself, plus the proof ID, input hash, draw payload, audit payload, and mode; only an attested proof is eligible for the public proof URL. This catches later proof-file edits, but it does not establish that the local binary or real-world candidate pool was unmodified before drawing. Do not describe the receipt as pre-draw server witnessing. -- `NotificationService` is app-layer because it bridges completed draws to the optional ClassIsland `SecRandom4Ci` plugin through v2 IPC. Use the source-compatible `SecRandom4Ci.Interface` DTOs; each draw channel only controls whether it is enabled, while `NotificationSettings.Default` owns one global set of service, duration, threshold, and built-in auto-close values. The built-in notification channel is the existing QuickDraw window, not a separate notification window: automatic QuickDraw delivery opens it during the rolling preview only for built-in or dual service types, then reveals the result; external-only delivery does not open it unless `UseBuiltInOnServiceFailure` (default enabled) invokes the backend-neutral fallback. This does not restrict a user-initiated QuickDraw window. +- `NotificationService` is app-layer because it bridges completed draws to the optional ClassIsland `SecRandom4Ci` plugin through v2 IPC. Use the source-compatible `SecRandom4Ci.Interface` DTOs; each draw channel only controls whether it is enabled, while `NotificationSettings.Default` owns one global set of service, duration, threshold, and built-in auto-close values. The built-in notification channel is the existing QuickDraw window, not a separate notification window: automatic QuickDraw delivery opens it during the rolling preview only for built-in or dual service types, then reveals the result; external-only delivery does not open it unless `UseBuiltInOnServiceFailure` (default enabled) invokes the backend-neutral fallback. This does not restrict a user-initiated QuickDraw window. The built-in floating window's position, monitor, offsets, and opacity are one global set stored on `NotificationSettings.Default` and edited only on the `settings.notification.floatingWindow` page; the per-channel `OverrideNotificationWindowSettings` is a legacy field that a load-time migration (`FloatingWindowSettingsUnifiedInitialized`) folds back to `false`. - `NotificationChannelSettings.NotificationServiceType` has four mutually exclusive backends: `0` built-in QuickDraw window, `1` ClassIsland, `2` both, and `3` the fullscreen result window. The legacy integers keep their meaning (they are persisted), so new channels are appended and never renumber `0`/`1`/`2`; the notification settings dropdown therefore binds `ItemsSource` + `SelectedItem` with an explicit value mapping instead of `SelectedIndex`. "Both" (`2`) never includes the fullscreen window — fullscreen is a standalone backend, so it cannot be combined with ClassIsland. `UsesFullscreenNotificationService` is the only test for it, and every consumer must use that plus `NotificationService.IsFullscreenPresentationAvailable`: on mobile (no desktop windows) the value degrades to the built-in channel rather than silently dropping the notification. - The fullscreen result window is its own window (`FullscreenNotificationWindow`) with its own appearance settings under `NotificationSettings.Fullscreen` (background mode — theme/solid/gradient/image — plus image blur, image opacity, accent, text switch, voice switch, animation style, countdown). It must not reuse or extend the QuickDraw window's placement/opacity/animation controls, and its settings must stay out of `NotificationChannelSettings` — that model is the per-draw-type channel selection, not a place for one backend's skin. Draw flows talk to it only through `NotificationService.BeginFullscreenPresentation` / `CompleteFullscreenPresentation` / `CancelFullscreenPresentation` with an immutable `FullscreenResultSnapshot` frozen at commit time; the window never re-queries ViewModels, candidates, or history. Only a successfully committed draw calls `Complete`, because completing is what selects and counts a text template. - The fullscreen window's presentation rules are semantic, not cosmetic. Text templates belong to the typewriter style only: `FullscreenTextAnimation.BuildLines(snapshot, includeTemplate)` is called with `includeTemplate: false` for direct/grid, and `FullscreenNotificationComposer` only fills `VoiceText` when `ShowText && AnimationStyle == Typewriter`, so a style without captions never narrates captions. `{result}` is template syntax — rendered output is the bare result text, never the literal braces. Typewriter speed comes from `FullscreenNotificationSettings.TypewriterCharactersPerSecond` (4–40) and must not be capped by a total duration, or long templates get truncated. The caption card (`S_Fullscreen_Content`: text switch, text-library entry, typewriter speed) sits directly under the animation-style selector and is collapsed for every other style, and its rows are plain `Grid` rows — never nested `fa:FASettingsExpander`s, because FluentAvalonia throws on card-in-card expansion. Its appearance defaults follow the theme: `BackgroundMode` (`FullscreenBackgroundMode`) defaults to `Theme` and has four mutually exclusive values (`Theme`/`Solid`/`Gradient`/`Image`) — the settings page shows only the selected mode's cards (solid `ColorPicker`, two gradient `ColorPicker`s plus a 0–360° angle slider, or image import/blur/opacity), `ResolveBackgroundAppearance()` is the only place that turns the config into render values (invalid mode/out-of-range values fall back, never crash the window), and the body text colour is derived from the resolved background's luminance rather than the app theme so a light solid or gradient stays readable. Colours are `Avalonia.Media.Color` in the config (persisted by the app-wide `ColorJsonConverter`), image/blur/opacity rows only apply in `Image` mode, `UseThemeAccentColor` defaults to on (`ThemeAccentColor.Resolve()` colours the result, the edge countdown bars and the idle scroller), and `BackgroundOpacity` defaults to 100. There is deliberately **no** dim/overlay setting: only `Image` mode gets the fixed `ImageOverlayOpacity` darkening it needs for legible text, while theme/solid/gradient are the user's own chosen colours and must not be dimmed on top. `Theme` mode paints the application theme's opaque surface colour as one flat fill — never a gradient and never accent-blended, and semi-transparent surface resources are rejected — because "follow the theme" means the app's own background, and a tinted gradient reads as an impure colour on a projector; the accent colour stays on the countdown, the edge bars and the result emphasis only. The accent colour is one card, not two: a mode dropdown picks follow-theme or custom, and the left-hand control swaps between the theme swatch and a `ColorPicker` bound to `AccentColorValue` (persisted as `#RRGGBB`). Display content (`S_Fullscreen_DisplayContent`) is one multi-select `sr:MultiComboBox` card listing number/name/avatar (`ShowResultNumber`/`ShowResultName`/`ShowResultAvatar`); `FullscreenNotificationComposer.ComposeResultText` composes the result caption at snapshot time, so a draw's caption cannot change under it — and **both** `CreateSnapshot` and `CreatePreviewSnapshot` must put those composed items into the snapshot (passing the raw items makes every display-content switch silently inert, which is what happened once). Avatar images come from each member's `DrawImageAttachedSettings`; the result view draws each avatar inline **to the left of that member's name** (photo circle, or a name-initial disc when the member has no image), and the typewriter style must attach them **after** its animation finishes because it rewrites `ResultHost` every frame (only direct/grid-goes-static reinsert through `ShowStatic`). `ShowResultNumber` defaults to **off** so the default caption is the name alone; number/name/avatar remain independent switches. Grid cards stay text-only. Multi-result captions must flow as **one** wrapped paragraph (results separated by a spacer, avatars inline via `InlineUIContainer`) instead of one text line per result — a class of 30 otherwise never fits a screen even at the auto-fit font size. The vignette is image-only and always dark: a white vignette on a light theme paints two white bands along the top and bottom edges and makes every "follow the theme" background look impure, so theme/solid/gradient backgrounds get no dimming or edge shading at all. `ResultFontSize` (32–240 px) is an upper bound, not a fixed size: the window takes `min(configured, auto-fit)` so several results still fit. The fullscreen channel deliberately owns **no** countdown or monitor setting of its own: the presenter reads `DisplayDuration` from `GetOverrideNotificationSettings(kind, Service)` and the window reads `EnabledMonitor` from `GetOverrideNotificationSettings(kind, NotificationWindow)` — those live in the notification channel, and duplicating them would let the two values disagree. The preview uses a one-shot `Complete(kind, snapshot, autoCloseSecondsOverride: 3)` instead of mutating real settings. The page debounces its saves (400 ms) and flushes the pending edit on unload, because `ConfigHandler.Save()` rewrites the whole `settings.json` and a colour/slider drag would otherwise write dozens of times per second. Covering the taskbar needs both full-screen geometry from `screen.Bounds` and a native topmost request (`IWindowFeatureService` + `WindowFeatures.Topmost`, re-asserted after show) — Avalonia's `Topmost` alone does not beat the taskbar, which is itself a topmost window. @@ -193,11 +193,11 @@ SecRandom/ - The control node (集控, `docs/client-protocol.md`) is the only remote-control ingress. Its device-owned switch, node identity, group id, endpoint, applied `desired_state` revision, and draw lock live in `data/config/control/node-state.json` through `IControlNodeStateStore` — never in `settings.json`, because a settings import must not be able to enable remote control. `LinkageDrawCoordinator.AuthorizeAsync` refuses every draw while that gate is locked, and `EvaluateGate` answers "would this raise a local password prompt?" so a remote command can be refused instead of leaving an unattended classroom machine waiting on a dialog. Read the endpoint through `ControlEndpointPolicy` (wss, or plaintext ws only to loopback). Declared capabilities must stay honest: only declare what `ControlCommandDispatcher` implements, and never implement `node.restart` (the service refuses it on purpose). A phone is only the console side (`MobileRemoteDrawViewModel` sends `draw.trigger` to nodes) and has no outbound node channel, so its branch of `BuildHost()` registers the neutral `UnlockedControlDrawGate` instead. That registration is mandatory, not cosmetic — `LinkageDrawCoordinator` is shared by both hosts, and a missing gate fails inside `Host.StartAsync` (it constructs `GlobalShortcutService`, whose draw-page ViewModels reach the gate) and takes the whole mobile host down. Do not register the unlocked gate for desktop: a real gate that disappears must fail loudly instead of silently unlocking every draw. **Which host runs the node is decided in exactly one place**, `AppHostShape.Resolve(isMobile, MobilePlatformServiceRoot.UsesDesktopMainView)` in `Mobile/AppHostShape.cs`, and `BuildHost()` reads only its result — the node runs on desktop **or tablet** (`RunsControlNode`), while a phone (`UsesUnlockedDrawGate`) has no outbound node channel. A tablet is both sides: it registers the **real** `ControlDrawGateService` plus the node services and the `settings.general.control` page, and reaches the *same* `MobileRemoteDrawViewModel` as the phone — desktop and tablet register the **desktop-layout view** as a `MainView` sidebar entry (`AddMainPage`), the phone keeps its keyed bottom-bar registration of `MobileRemoteDrawPage` (`MobilePageIds.RemoteDraw`), and **one ViewModel serves both views** (never a second VM; see the 远程抽取页的宿主矩阵 bullet below). Never give a tablet the unlocked gate (its remote lock would silently stop working and local draws would be let through), and never give a phone the real one. Remote draws on a tablet have no `MainWindow`: `App.ShowMainWindowCoreAsync` only creates a desktop window when `App.IsDesktop`, and `RemoteDrawFocusPlan.Resolve` returns `RemoteDrawSurface.SingleViewHost` so no window code runs — the target page is selected in `MainView` instead. Raising the app from the background is an OS restriction on Android/iPadOS, not something the client can do. - Floating-window course hiding records linkage-owned prior visibility and current user intent. Do not restore a window that the user hid manually while a course break was active. - **远程抽取页的宿主矩阵(一份 VM + 两个视图)**:`MobileRemoteDrawViewModel` 是**唯一一份** ViewModel(设备列表、读名单/奖池、条件、抽取、重置、回执解析与四态文案)——协议逻辑分叉就是这个项目吃过两次亏的地方,谁都不许为某个宿主复制一份。**UI 则按宿主分叉**:桌面/平板用桌面主页面版式的 `Views/MainPages/RemoteDrawPage.axaml(.cs)`(左侧结果区 + 右侧控制区,与点名/抽奖同一套观感),手机保持 `Views/Mobile/MobileRemoteDrawPage.axaml(.cs)` 的竖排表单。视图只做展示与绑定:需要的新展示态加进共享 VM(例如 `DrawnCountText`),绝不在视图里自己算,否则两侧同一天会说两句话。手机页的版式是**上结果、下控制**:结果/失败文案只出现在顶部结果区,抽取按钮下方只留"正在下发"这类临时进行态;结果区封顶 200 且内部可滚动,未抽时空态只有两行,不能把控制项顶出屏幕。**设备列表要标出本机**:`DeviceRow.IsSelf` 由 `DeviceRow.IsSameNode(本机 node_id, 行 node_id)` 在共享 VM 里算出(大小写与空白差异不算两台;本机没配置身份、或手机没有节点时一台都不标),行内给一个次级样式的徽章,选中本机时给出说明但**不禁用**选择,且本机**不得从列表里过滤掉**。**设备加载态只能在共享 VM 里收口**(`BeginDeviceLoad`/`EndDeviceLoad` + 序号取代):成功、失败、0 台、异常、被更新的请求取代都必须清掉 `IsLoadingDevices` **以及那句"正在读取设备"进度文案**——这条流程曾在成功路径上只清布尔量,把"正在读取设备"的残影留在状态行上(三端同错,因为状态在共享层)。**结果区只显示远端回执里真的返回了什么**(`detail.drawn` → `DrawnMembers`):没有回执就不列成员,只显示状态文案(还没抽/失败/超时/被拒),前端不造结果。`AppHostShape` 负责回答"怎么挂":桌面与平板没有底部导航栏,注册为 **`MainView` 侧栏主页面**(`UsesRemoteDrawSidebarPage` → `AddMainPage`),手机注册为 **底部第 5 档 keyed 页面**(`UsesRemoteDrawBottomTab` → `AddKeyedTransient(MobilePageIds.RemoteDraw)`),两者恰好一个为真,两个视图共用同一个页面 id `main.remoteDraw`。**侧栏顺序**:桌面/平板上「远程抽取」必须排在**「抽奖」下面**——顺序由 `AddMainPage` 的注册顺序 + `PageLocation` 决定(桌面主页都在 `Bottom` 组,`Top` 组是空的),因此那条注册紧跟在 `AddMainPage` 之后、`AddMainPage` 之前,并由 `TabletControlHostTests.侧栏顺序_远程抽取紧跟在抽奖之后` 钉住;手机底部顺序不受此影响。 -- Floating window edge docking uses `StickToEdge`: on drag release it snaps only when near the current display's horizontal work-area edge. Dragging stays in valid display work areas and can cross only to physically adjacent displays. At startup, a saved position that does not fully fit a current display work area is restored directly as a docked handle at an available display edge. `StickToEdgeRecoverSeconds` controls auto-collapse (`0` disables collapse); the collapsed handle and restoration transition remain anchored at the docked left/right side center. +- Floating window edge docking uses `StickToEdge`: on drag release it snaps only when near the current display's horizontal work-area edge. Dragging stays in valid display work areas and can cross only to physically adjacent displays. At startup, a saved position that does not fully fit a current display work area is restored directly as a docked handle at an available display edge. `StickToEdgeRecoverSeconds` controls auto-collapse (`0` disables collapse); the collapsed handle and restoration transition remain anchored at the docked left/right side center. The collapsed handle's face is `StickToEdgeDisplayStyle` (0 图标 / 1 文字 / 2 箭头), and `FloatingWindowDockHandle` (`SecRandom.Core/Services/FloatingWindow/`) owns the whole rule set: 文字 uses `StickToEdgeDisplayText` (empty ⇒ `C_PickButtonText`), 图标 uses `StickToEdgeDisplayIconGlyph` plus `StickToEdgeDisplayIconImage`, and 箭头 is a real `FluentIcon` (`ChevronLeft/RightFilled`), never a `"<"`/`">"` character. Text is normalized to code points, control characters and emoji are dropped, and the limit is one character for Chinese but four for other languages — storage always allows four so switching the UI language cannot silently truncate a saved value, and the rendered font size shrinks as the text grows. An imported handle image lives in the same `data/images/floating-window-icons` directory as custom buttons, so every `FloatingWindowIconService.Prune` call site must keep `StickToEdgeDisplayIconImage` in its keep set. The three display fields are read-only on the control plane: they are this machine's appearance choice and the image name points at a local file. - Basic settings are active behavior: the primary `MainWindow` alone consumes startup visibility, topmost mode, and background-resident close behavior; `AutoSaveWindowSize` preserves separate geometry/maximized state for the primary and settings windows. Selecting UIAccess topmost for either primary or floating windows persists the choice and requests a restart; `SecRandom.Desktop/UiAccessStartup.cs` follows `killtimer0/uiaccess` by setting `TokenUIAccess` on a duplicate of the elevated bootstrap token before Avalonia starts, while UAC cancellation or preparation failure uses ordinary topmost only for that run. `DesktopIntegrationService` owns user-level autostart and `secrandom://` registration for Windows, Linux, and macOS; a failed registration must leave its setting disabled rather than persisting a false success. Those entries outlive the process, so in a portable package they launch the stable `SecRandomLauncher` at the package root (`Utils.TryGetPortableLauncherPath`) instead of the `SecRandom.Desktop` executable inside the activated `app-*` payload, which an update replaces; installed packages keep the executable beside the app. - `TopmostMode.UiAccess` is Windows-only process capability, not a separate window API. Release builds opt into it through the desktop UIAccess manifest, Authenticode-sign `SecRandom.Desktop.exe`, and install under Program Files; ordinary/debug builds retain the normal manifest and `DesktopIntegrationService` falls back to ordinary topmost when the token is absent. - Page IDs follow root rules: `main.xxx`, `settings.xxx`, `settings.group.xxx`. -- V2-parity settings pages currently use root IDs such as `settings.personalized.floatingWindow`, `settings.notification`, `settings.general.security`, `settings.linkage`, `settings.notification.voiceMusic`, `settings.history`, `settings.update`, and `settings.more`; register them in `BuildHost()` instead of manually editing navigation UI. Hidden pages like `settings.logs` still need Host registration even though they are not shown in the sidebar. +- V2-parity settings pages currently use root IDs such as `settings.personalized.floatingWindow`, `settings.notification`, `settings.general.security`, `settings.linkage`, `settings.notification.voiceMusic`, `settings.notification.floatingWindow`, `settings.history`, `settings.update`, and `settings.more`; register them in `BuildHost()` instead of manually editing navigation UI. Hidden pages like `settings.logs` still need Host registration even though they are not shown in the sidebar. - The log viewer page ID is `settings.logs`; keep it hidden from the settings sidebar and route the settings more-options “查看日志” command through navigation instead of opening a separate window. The same menu's final, separated `反馈` action opens a host-scoped transient `FeedbackDrawer` through the existing right-side `DrawerHost`; temporary close preserves its draft, while cancel clears it. - Toasts are available from views via `this.ShowWarningToast(...)` / `ShowErrorToast(...)`; shell views inject `AppToastAdorner` on load. diff --git a/SecRandom/App.axaml.cs b/SecRandom/App.axaml.cs index a232c22a8..8c984b9ed 100644 --- a/SecRandom/App.axaml.cs +++ b/SecRandom/App.axaml.cs @@ -38,12 +38,14 @@ using SecRandom.Core.Models.SubConfigs; using SecRandom.Core.Services.Config; using SecRandom.Core.Services.Notification; +using SecRandom.Core.Services.Stats; using SecRandom.Core.Services.ControlNode; using SecRandom.Core.Services.Draw; using SecRandom.Core.Services; using SecRandom.Core.Services.Presentation; using SecRandom.Core.Services.Views; using SecRandom.Core.Services.Archive; +using SecRandom.Core.Services.DataRoot; using SecRandom.Core.Services.Verification; using SecRandom.Core.Services.Logging; using SecRandom.Core.Services.SingleInstance; @@ -68,6 +70,7 @@ using SecRandom.Core.Views; using SecRandom.Shared.Models.Ipc; using SecRandom.Shared; +using SecRandom.Shared.DataRoot; using SecRandom.Helpers; using AppearanceSettingsConfig = SecRandom.Core.Models.SubConfigs.Personalized.AppearanceSettingsConfig; using PerformanceSettingsConfig = SecRandom.Core.Models.SubConfigs.General.PerformanceSettingsConfig; @@ -131,6 +134,7 @@ using FloatingWindowButtonsSettingsPage = SecRandom.Views.SettingsPages.Personalized.FloatingWindowButtonsSettingsPage; using FullscreenNotificationSettingsPage = SecRandom.Views.SettingsPages.Notification.FullscreenNotificationSettingsPage; using LotteryNotificationSettingsPage = SecRandom.Views.SettingsPages.Notification.LotteryNotificationSettingsPage; +using NotificationFloatingWindowSettingsPage = SecRandom.Views.SettingsPages.Notification.NotificationFloatingWindowSettingsPage; using QuickDrawNotificationSettingsPage = SecRandom.Views.SettingsPages.Notification.QuickDrawNotificationSettingsPage; using RollCallNotificationSettingsPage = SecRandom.Views.SettingsPages.Notification.RollCallNotificationSettingsPage; using TextLibrarySettingsPage = SecRandom.Views.SettingsPages.Notification.TextLibrarySettingsPage; @@ -148,6 +152,24 @@ public partial class App : Application private static Window? _quickDrawWindow; private static NotificationChannelSettings? _quickDrawNotificationSettings; private static bool _positioningQuickDrawWindow; + + /// + /// 本次通知已经算好的自适应前景方案。一次通知只采样一次:预览开始时算好,结果揭晓时复用, + /// 否则滚动动画播放到一半再换前景色,看起来就是闪一下。 + /// + private static AdaptiveTheme? _quickDrawNotificationTheme; + + /// 采样区在卡片矩形之外再向外扩一圈:贴着卡片的桌面才是肉眼看到的对比背景。 + private const int NotificationBackdropSampleMarginPixels = 48; + + /// 少于这么多像素说明区域几乎全被剔除(例如贴屏边),结论不可信。 + private const int NotificationBackdropMinimumSamples = 256; + + /// 采样上限:超过它就用应用主题,绝不为了配色阻塞抽取开始。 + private static readonly TimeSpan NotificationBackdropSampleTimeout = TimeSpan.FromMilliseconds(60); + + private const int NotificationFadeInSteps = 6; + private static readonly TimeSpan NotificationFadeInStepDelay = TimeSpan.FromMilliseconds(15); private static MainWindow? _mainWindow; private static MainWindow? _settingsWindow; private static Task? _runtimeServicesStartupTask; @@ -165,8 +187,6 @@ public partial class App : Application private readonly object _shutdownGate = new(); private bool _isStopping; private bool _isOobeActive; - private bool _settingsIntegrityConfirmationPending; - private SettingsIntegrityService? _settingsIntegrity; private StyleInclude? _reducedMotionStyles; private FloatingWindowSettingsConfig? _observedFloatingWindowSettings; private bool _observesFloatingWindowConfigHandler; @@ -202,14 +222,16 @@ public override void Initialize() { TouchInputModeAssist.Initialize(); var isMobile = PlatformStartupContext.Current is MobilePlatformServiceRoot; + var isDataRootMigration = DataRootLaunchState.IsMigration; if (isMobile) Utils.ConfigureMobileDataRoot(); - else - _desktopDataRootPreparation = Utils.PrepareDesktopDataRoot(); + else if (!isDataRootMigration) + // The migration window owns the move; it must not lock a root or read settings before the move is done. + _desktopDataRootPreparation = Utils.PrepareDesktopDataRoot(GlobalConstants.IsDevelopment); // 初始化语言 var mainConfig = new MainConfigModel(); - var settings = _desktopDataRootPreparation is { IsPortablePackage: true, IsWritable: false } + var settings = isDataRootMigration || _desktopDataRootPreparation is { IsWritable: false } ? mainConfig : LoadStartupSettings(mainConfig); var culture = settings.Basic.Language switch @@ -253,9 +275,16 @@ public override void OnFrameworkInitializationCompleted() _desktopLifetime = desktop; IsDesktop = true; - if (_desktopDataRootPreparation is { IsPortablePackage: true, IsWritable: false } preparation) + if (DataRootLaunchState.MigrationId is { } migrationId) { - desktop.MainWindow = CreatePortableDataRootFailureHost(desktop, preparation); + desktop.MainWindow = CreateDataRootMigrationHost(desktop, migrationId); + base.OnFrameworkInitializationCompleted(); + return; + } + + if (_desktopDataRootPreparation is { IsWritable: false } preparation) + { + desktop.MainWindow = CreateDataRootFailureHost(desktop, preparation); base.OnFrameworkInitializationCompleted(); return; } @@ -315,26 +344,6 @@ public override void OnFrameworkInitializationCompleted() return; } - // 防篡改校验是设置文件的启动闸门:记录不符时按配置自动恢复,或先用安全密码确认当前内容 - _settingsIntegrity = IAppHost.GetService(); - if (_settingsIntegrity.GetPendingMismatch() is { } settingsMismatch) - { - if (IAppHost.GetService().Data.SettingsIntegrityAction - == SettingsIntegrityAction.AutoRestore) - { - WriteDesktopStartupDiagnostic("Settings integrity check is attempting automatic recovery."); - ShowSettingsIntegrityRecovery(desktop, startupProtocolUri, settingsMismatch); - } - else - { - WriteDesktopStartupDiagnostic("Settings integrity check requires confirmation."); - ShowSettingsIntegrityGate(desktop, startupProtocolUri, settingsMismatch); - } - - base.OnFrameworkInitializationCompleted(); - return; - } - try { WriteDesktopStartupDiagnostic("Continuing desktop startup."); @@ -650,7 +659,7 @@ private void ApplyFloatingWindowStartupVisibility() DispatcherPriority.Loaded); } - /// 创建主窗或右侧副窗,并接好托盘菜单与字段回收。 + /// 创建主窗或另一侧的副窗,并接好托盘菜单与字段回收。 private static FloatingWindow CreateFloatingWindow(bool isSecondary) { var window = new FloatingWindow(isSecondary); @@ -673,8 +682,8 @@ private static IEnumerable FloatingWindows() } /// - /// 按"左右两侧同时显示"设置布置悬浮窗:开启时主窗钉右、副窗钉左;关闭时收起副窗并解除钉边, - /// 主窗留在右侧(右侧才是主浮窗,关掉两侧显示后不该让窗口跳到另一边)。 + /// 按"左右两侧同时显示"设置布置悬浮窗:开启时主窗钉在它原本那一侧、副窗钉在另一侧; + /// 关闭时收起副窗并解除钉边,主窗留在原来那一侧。 /// private void ApplyFloatingWindowLayout() { @@ -682,7 +691,11 @@ private void ApplyFloatingWindowLayout() return; var showOnBothSides = IAppHost.GetService().Data.EffectiveFloatingWindowSettings.ShowOnBothSides; - primary.SetEdgePinned(showOnBothSides, onLeft: false); + + // 主窗钉在哪侧由它此刻所在的位置决定,而不是写死右侧:用户原本把单扇浮窗放在左边时, + // 开启两侧显示不能把它搬到右边,否则关掉开关后就回不到原来那一侧了。 + var mainOnLeft = showOnBothSides && primary.IsOnLeftSide; + primary.SetEdgePinned(showOnBothSides, onLeft: mainOnLeft); if (!showOnBothSides) { @@ -699,7 +712,7 @@ private void ApplyFloatingWindowLayout() { secondary = CreateFloatingWindow(isSecondary: true); _secondaryFloatingWindow = secondary; - secondary.SetEdgePinned(true, onLeft: true); + secondary.SetEdgePinned(true, onLeft: !mainOnLeft); // 两侧高度统一时,副窗的纵向锚点跟着主窗走;先在它打开之前把锚点对齐, // 副窗自己的启动定位就会落在与主窗相同的高度上。 @@ -720,7 +733,7 @@ private void ApplyFloatingWindowLayout() return; } - secondary.SetEdgePinned(true, onLeft: true); + secondary.SetEdgePinned(true, onLeft: !mainOnLeft); Dispatcher.UIThread.Post(AlignFloatingWindowAnchors, DispatcherPriority.Loaded); } @@ -876,176 +889,6 @@ private FirstRunOobeWindow CreateFirstRunOobe( return oobe; } - /// - /// 设置文件防篡改校验未通过时的启动闸门。确认流程与首次运行向导一致: - /// 先把闸门窗口作为主窗口,待用户用安全密码接受当前设置文件后再继续正常启动。 - /// - private void ShowSettingsIntegrityGate( - IClassicDesktopStyleApplicationLifetime desktop, - string? startupProtocolUri, - SettingsIntegrityMismatch mismatch, - string? recoveryFailure = null) - { - _settingsIntegrityConfirmationPending = true; - var gate = CreateSettingsIntegrityGate(desktop, startupProtocolUri, mismatch, recoveryFailure); - desktop.MainWindow = gate; - gate.Show(); - } - - /// - /// 篡改处理方式为「自动恢复」时的启动流程:先从备份恢复设置文件,成功后自动重启应用; - /// 没有可用备份或恢复失败则回退到安全密码确认闸门,并把失败原因写进确认对话框。 - /// - private void ShowSettingsIntegrityRecovery( - IClassicDesktopStyleApplicationLifetime desktop, - string? startupProtocolUri, - SettingsIntegrityMismatch mismatch) - { - var host = CreateStartupGateWindow(); - host.Background = this.FindResource("SolidBackgroundFillColorBaseBrush") as IBrush; - host.Content = CreateIntegrityRecoveryContent(SecurityResources.M_IntegrityRecovering, showProgress: true); - desktop.MainWindow = host; - - // Opened 在 Dispatcher 事件循环内异步运行,恢复期间界面不会阻塞 - host.Opened += async (_, _) => - { - var outcome = await IAppHost.GetService().TryRecoverAsync(); - if (outcome.Succeeded) - { - host.Content = CreateIntegrityRecoveryContent( - string.Format( - SecurityResources.M_IntegrityRecoverSuccessFormat, - outcome.FromCloud ? SecurityResources.M_IntegritySourceCloud : SecurityResources.M_IntegritySourceLocal, - outcome.BackupName ?? SecurityResources.M_IntegrityUnknownValue, - outcome.PreRestorePath ?? SecurityResources.M_IntegrityUnknownValue), - showProgress: false); - WriteDesktopStartupDiagnostic("Settings file restored from backup; restarting the application."); - await Task.Delay(TimeSpan.FromSeconds(3)); - Restart(); - return; - } - - var failure = DescribeIntegrityRecoveryFailure(outcome); - WriteDesktopStartupDiagnostic($"Settings integrity automatic recovery failed: {failure}"); - // 先显示确认闸门再关闭本窗口,避免出现「最后一个窗口关闭」而直接结束进程 - ShowSettingsIntegrityGate(desktop, startupProtocolUri, mismatch, failure); - host.Close(); - }; - - host.Show(); - } - - private static string DescribeIntegrityRecoveryFailure(SettingsIntegrityRecoveryResult outcome) => - outcome.Status switch - { - SettingsIntegrityRecoveryStatus.CloudNotSignedIn => SecurityResources.M_IntegrityNotSignedIn, - SettingsIntegrityRecoveryStatus.Failed => string.IsNullOrWhiteSpace(outcome.Detail) - ? SecurityResources.M_IntegrityBackupInvalid - : outcome.Detail!, - _ => SecurityResources.M_IntegrityNoBackup - }; - - private Control CreateIntegrityRecoveryContent(string message, bool showProgress) - { - var content = new StackPanel - { - Spacing = 12, - MaxWidth = 560, - HorizontalAlignment = HorizontalAlignment.Center, - VerticalAlignment = VerticalAlignment.Center - }; - - if (showProgress) - { - content.Children.Add(new FAProgressRing - { - IsActive = true, - Width = 40, - Height = 40, - HorizontalAlignment = HorizontalAlignment.Center - }); - } - - content.Children.Add(new TextBlock - { - Text = SecurityResources.M_IntegrityRecoverTitle, - FontSize = 20, - FontWeight = FontWeight.SemiBold, - TextWrapping = TextWrapping.Wrap, - TextAlignment = TextAlignment.Center, - HorizontalAlignment = HorizontalAlignment.Center - }); - content.Children.Add(new TextBlock - { - Text = message, - TextWrapping = TextWrapping.Wrap, - TextAlignment = TextAlignment.Center, - HorizontalAlignment = HorizontalAlignment.Center - }); - return content; - } - - private Window CreateSettingsIntegrityGate( - IClassicDesktopStyleApplicationLifetime desktop, - string? startupProtocolUri, - SettingsIntegrityMismatch mismatch, - string? recoveryFailure) - { - var host = CreateStartupGateWindow(); - - // Opened 在 Dispatcher 事件循环内异步运行,不会阻塞 UI 线程 - host.Opened += async (_, _) => - { - var fallback = SecurityResources.M_IntegrityUnknownValue; - var message = string.Format( - SecurityResources.M_IntegrityDetectedFormat, - mismatch.RecordedAtUtc.ToLocalTime().ToString("g"), - string.IsNullOrWhiteSpace(mismatch.RecordedAppVersion) ? fallback : mismatch.RecordedAppVersion, - mismatch.FileModifiedAtUtc?.ToLocalTime().ToString("g") ?? fallback); - if (!string.IsNullOrWhiteSpace(recoveryFailure)) - message = $"{string.Format(SecurityResources.M_IntegrityRecoverFailedFormat, recoveryFailure)}{Environment.NewLine}{Environment.NewLine}{message}"; - var dialog = new FATaskDialog - { - XamlRoot = host, - Title = SecurityResources.M_IntegrityDialogTitle, - Header = SecurityResources.M_IntegrityDetectedHeader, - Content = new TextBlock { TextWrapping = TextWrapping.Wrap, Text = message } - }; - dialog.Buttons.Add(new FATaskDialogButton(SecurityResources.C_IntegrityExit, "exit")); - dialog.Buttons.Add(new FATaskDialogButton(SecurityResources.C_IntegrityAccept, "accept") { IsDefault = true }); - - if (!Equals(await dialog.ShowAsync(), "accept")) - { - host.Close(); - RequestDesktopShutdown(); - return; - } - - var accepted = await IAppHost.GetService().AuthorizePasswordAsync( - host, - () => - { - _settingsIntegrity?.AcceptCurrentFile(); - return Task.CompletedTask; - }); - if (!accepted) - { - // 未通过密码确认即视为拒绝当前设置文件,不再继续启动 - host.Close(); - RequestDesktopShutdown(); - return; - } - - _settingsIntegrityConfirmationPending = false; - WriteDesktopStartupDiagnostic("Settings integrity confirmed, continuing desktop startup."); - ContinueDesktopStartup(desktop, startupProtocolUri); - host.Close(); - ShowMainWindow(); - }; - - return host; - } - /// /// 启动闸门共用的宿主窗口:全屏透明无边框,内容由闸门自己填充, /// 保证在 Host 启动前也能弹出一个不抢任务栏位置的遮罩窗口。 @@ -1114,20 +957,21 @@ private static async Task ForwardToRunningInstanceAsync(string? startupPro .ConfigureAwait(true); } - private static Window CreatePortableDataRootFailureHost( + private static Window CreateDataRootFailureHost( IClassicDesktopStyleApplicationLifetime desktop, Utils.DesktopDataRootPreparationResult preparation) { var host = new SecRandomTmpRootWindow(); host.Opened += async (_, _) => { + var isPortable = preparation.IsPortablePackage; var dialog = new FATaskDialog { XamlRoot = host, - Title = CR.M_PortableDataDirectoryUnavailableTitle, - Header = CR.M_PortableDataDirectoryUnavailableTitle, + Title = isPortable ? CR.M_PortableDataDirectoryUnavailableTitle : CR.M_DataRootUnavailableTitle, + Header = isPortable ? CR.M_PortableDataDirectoryUnavailableTitle : CR.M_DataRootUnavailableTitle, Content = string.Format( - CR.M_PortableDataDirectoryUnavailableContent, + isPortable ? CR.M_PortableDataDirectoryUnavailableContent : CR.M_DataRootUnavailableContent, preparation.DataRoot, preparation.ErrorMessage ?? CR.M_UnknownError) }; @@ -1141,6 +985,14 @@ private static Window CreatePortableDataRootFailureHost( return host; } + private static Window CreateDataRootMigrationHost( + IClassicDesktopStyleApplicationLifetime desktop, + Guid migrationId) + { + // The migration runs before the Host exists: no config, no DI, no single-instance acquisition. + return new DataRootMigrationWindow(migrationId, desktop); + } + /// /// 处理来自后续实例的 IPC 命令(第一个实例专用)。 /// 回调来自后台线程,需通过 切换到 UI 线程。 @@ -1151,8 +1003,6 @@ private void OnIpcCommandReceived(string command) { if (_isOobeActive) return; - if (!SettingsIntegrityCommandGate.IsAllowed(_settingsIntegrityConfirmationPending)) - return; switch (command) { @@ -1182,23 +1032,21 @@ private void OnIpcCommandReceived(string command) }); } + /// 首次引导是否仍在进行;v2 自动化管道据此拒绝所有命令。 + public bool IsOobeActive => _isOobeActive; + private Task OnIpcRequestReceived(IpcRequestEnvelope request, CancellationToken cancellationToken) { if (_isOobeActive) return Task.FromResult(new IpcResponseEnvelope(true, "url", new IpcBusinessResult("error", "初始设置尚未完成。", "oobe_required"))); - if (_settingsIntegrityConfirmationPending) - return Task.FromResult(IpcResponseEnvelope.TransportFailure("url", "integrity_confirmation_required", "设置文件完整性尚未确认。")); return IAppHost.GetService().HandleIpcAsync(request, cancellationToken); } private void HandleProtocolUri(string value) { - if (!SettingsIntegrityCommandGate.IsAllowed(_settingsIntegrityConfirmationPending)) - return; - ObserveTask(IAppHost.GetService().HandleUrlAsync(value), "Protocol URL handling failed."); } @@ -1323,23 +1171,12 @@ private void BuildHost(IPlatformServiceRoot platform) client.Timeout = TimeSpan.FromSeconds(15); }); services.AddSingleton(); - // SECTL 账号与云备份在桌面和移动端都注册:移动端用自定义 scheme + 系统浏览器完成 - // 授权(见 MobileAuthRedirectBroker),云备份的归档引擎本来就是平台中立的。 + // SECTL 账号在桌面和移动端都注册:移动端用自定义 scheme + 系统浏览器完成授权(见 MobileAuthRedirectBroker)。 services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddHostedService(serviceProvider => serviceProvider.GetRequiredService()); - services.AddHttpClient("sectl-cloud", client => - { - client.BaseAddress = new Uri("https://appwrite.sectl.cn/"); - client.Timeout = TimeSpan.FromSeconds(60); - }); - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - services.AddHostedService(serviceProvider => - serviceProvider.GetRequiredService()); services.AddSingleton(); services.AddSingleton(); services.AddHostedService(); @@ -1384,9 +1221,7 @@ private void BuildHost(IPlatformServiceRoot platform) services.AddSingleton(); services.AddSingleton(); } - services.AddSingleton(); services.AddSingleton(); - services.AddSingleton(); services.AddSingleton(); services.AddHttpClient(client => client.Timeout = TimeSpan.FromSeconds(3)); @@ -1506,6 +1341,17 @@ private void BuildHost(IPlatformServiceRoot platform) services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); + + // v2 自动化管道:与集控读/写处理器共用同一套校验与 UI 线程边界。 + services.AddSingleton(SingleInstanceService.Instance); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddHostedService(provider => provider.GetRequiredService()); + services.AddSingleton(); + services.AddHostedService(provider => provider.GetRequiredService()); // 远程抽取:解析/闸门/回执在 ControlDrawTriggerHandler 里(可脱离界面单测), // 真正动手的那一步在 ControlPageDrawExecutor 里(要回到 UI 线程)。 services.AddSingleton(); @@ -1540,16 +1386,6 @@ private void BuildHost(IPlatformServiceRoot platform) services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); - services.AddSingleton(serviceProvider => new SettingsIntegrityService( - serviceProvider.GetRequiredService(), - serviceProvider.GetRequiredService(), - serviceProvider.GetRequiredService(), - serviceProvider.GetRequiredService>())); - services.AddSingleton(serviceProvider => new SettingsIntegrityRecoveryService( - serviceProvider.GetRequiredService(), - serviceProvider.GetRequiredService(), - serviceProvider.GetRequiredService(), - serviceProvider.GetRequiredService>())); // 接入令牌:自建集控的节点凭据,独立加密存放(data/config/security/control-node.json)。 // 注册在**共享分支**里:手机端虽然不跑节点,但远程抽取页同样要在"未登录 SECTL"时可用, @@ -1599,6 +1435,7 @@ private void BuildHost(IPlatformServiceRoot platform) services.AddSingleton(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); // "远程抽取"页的 ViewModel:**桌面/平板/手机三个宿主共用同一份**。它只跟协议有关, // 与谁是控制端/被控端无关,因此注册在共享分支;页面每次进入都重建(FAFrame 不快取), // 它自己会记住上次选中的设备,不需要做成单例。 @@ -1694,6 +1531,12 @@ private void BuildHost(IPlatformServiceRoot platform) services.AddSettingsPage(Langs.SettingsPages.General.Verification .Resources.Page_Title); services.AddSettingsPage(Langs.Common.Resources.Settings_Backup); + if (!isMobile) + { + // 数据目录只能由桌面壳迁移(手机数据根位于系统沙盒,无法选择也无法整体搬迁)。 + services.AddSettingsPage( + Langs.SettingsPages.General.Storage.Resources.Page_Title); + } if (hostShape.RunsControlNode) { // 集控节点与集控设置页成对出现:跑节点的宿主(桌面/平板)才该看到这个页面。 @@ -1742,6 +1585,8 @@ private void BuildHost(IPlatformServiceRoot platform) Langs.SettingsPages.Picking.Resources.Page_QuickDraw); services.AddSettingsPage( Langs.SettingsPages.Picking.Resources.Page_Lottery); + services.AddSettingsPage( + Langs.SettingsPages.Picking.Resources.Page_RandomNumber); services.AddGroup(new PageGroupInfo( Langs.Common.Resources.Settings_Notification, "settings.notification", @@ -1762,6 +1607,10 @@ private void BuildHost(IPlatformServiceRoot platform) .Settings_QuickDrawNotification); services.AddSettingsPage(Langs.Common.Resources .Settings_LotteryNotification); + // 内置通知浮窗的窗口设置(位置 / 显示器 / 偏移 / 不透明度)独立成页,紧贴全屏渠道页之上: + // 两者都是"结果用什么窗口显示"的设置,而渠道页现在只保留启用、动画与通知服务。 + services.AddSettingsPage( + Langs.SettingsPages.Notification.Resources.Page_FloatingWindow); // 全屏渠道的两页:外观/动画设置 + 文案库管理。分开放是因为文案库是一张会一直在长的 // 清单(导入、编辑、统计),而设置页只该放"外观与行为"。 services.AddSettingsPage( @@ -2092,9 +1941,9 @@ private async Task StopAsync(bool requestLifetimeShutdown) } } - public async void Restart() + public async void Restart(IEnumerable? arguments = null) { - var startInfos = CrashRecoveryRuntime.CreateRestartStartInfos([]); + var startInfos = CrashRecoveryRuntime.CreateRestartStartInfos(arguments ?? []); TrySaveConfigForCrashRecovery(); SingleInstanceService.Instance.Dispose(); @@ -2619,6 +2468,15 @@ public static void ToggleMainWindow(string? pageId = null) () => ShowMainWindowCoreAsync(pageId)), "Main window authorization failed."); } + /// 主窗口当前是否可见;IPC 的 state.windows 用它读取真实状态。 + public static bool IsMainWindowVisible => _mainWindow is { IsVisible: true }; + + /// 设置窗口当前是否可见。 + public static bool IsSettingsWindowVisible => _settingsWindow is { IsVisible: true }; + + /// 悬浮窗是否被用户期望显示(不受课程联动临时隐藏影响)。 + public static bool IsFloatingWindowVisible => _floatingWindow is { UserWantsVisible: true }; + public static void SetMainWindowVisibility(string action, string? pageId = null) { ObserveTask(SetMainWindowVisibilityCoreAsync(action, pageId), "Main window visibility update failed."); @@ -2812,9 +2670,10 @@ await IAppHost.GetService().ShowAsync( } } - public static void ShowQuickDrawWindow() + /// 打开闪抽; 是浮窗长按快选选好的人数,默认 1 人。 + public static void ShowQuickDrawWindow(int count = 1) { - ObserveTask(ShowQuickDrawWindowAsync(), "Quick draw window action failed."); + ObserveTask(ShowQuickDrawWindowAsync(count), "Quick draw window action failed."); } public static void ShowQuickDrawNotificationWindow( @@ -2833,26 +2692,173 @@ public static void ShowQuickDrawNotificationWindow( public static Task ShowQuickDrawNotificationPreviewWindowAsync(NotificationChannelSettings windowSettings) { - return Dispatcher.UIThread.InvokeAsync(() => + return Dispatcher.UIThread.InvokeAsync(async () => { _quickDrawNotificationSettings = windowSettings; var quickDraw = IAppHost.GetService(); - quickDraw.NotificationOpacity = Math.Clamp(windowSettings.Transparency, 20, 100); - var window = GetOrCreateQuickDrawWindow(); + await PrepareQuickDrawNotificationWindowAsync(quickDraw, windowSettings); + }); + } + + /// + /// 建窗、定位、背景采样与淡入合成的唯一入口。 + /// + /// + /// 时序是这次改动的核心:窗口先以 0 不透明度占位, + /// 在后台算亮度,主题落定后才淡入。于是"建窗"和"采样"是并行的,用户感知到的是卡片带着正确 + /// 的前景色一起出现,而不是先白后黑闪一下。 + /// + private static async Task PrepareQuickDrawNotificationWindowAsync( + QuickDrawPageViewModel quickDraw, + NotificationChannelSettings settings) + { + var window = GetOrCreateQuickDrawWindow(); + quickDraw.NotificationOpacity = Math.Clamp(settings.Transparency, 20, 100); + + // 采样先扔到后台线程,再建窗/排版/定位:两者并行,CPU 抓屏的那几毫秒被窗口工作完全盖住。 + // 此刻窗口还没排版,采样区按 MinWidth/MinHeight 估算;Show 之后如果发现实际卡片偏离估算 + // (高 DPI 下 Show 之前拿不到真实 RenderScaling、或 SizeToContent 比最小值大),再补采一次。 + var predictedRect = TryResolveQuickDrawNotificationTargetRect(window, settings, null, out var predicted) + ? predicted + : (PixelRect?)null; + var themeTask = _quickDrawNotificationTheme is null + ? ResolveQuickDrawNotificationThemeAsync(window, settings) + : null; + + var fadeIn = !window.IsVisible; + if (fadeIn) + { + window.Opacity = 0; + window.Show(); + } + + ApplyQuickDrawWindowFocusFree(window); + + // Show 之后先跑一轮渲染/排版:SizeToContent 窗口的尺寸与 RenderScaling 到这里才是最终值, + // 而窗口定位必须用它算出来。 + await Dispatcher.UIThread.InvokeAsync(() => { }, DispatcherPriority.Render).GetTask(); + PositionQuickDrawNotificationWindow(window, settings); + + if (themeTask is not null) + { + if (predictedRect is { } predictedTarget + && TryResolveQuickDrawNotificationTargetRect(window, settings, window.Bounds.Size, out var actual) + && !IsCloseEnough(predictedTarget, actual)) + themeTask = ResolveQuickDrawNotificationThemeAsync(window, settings, window.Bounds.Size); + + ApplyQuickDrawNotificationTheme(quickDraw, await themeTask); + } + + if (fadeIn) + // 淡入不 await:抽取已经开始,绝不能为了 90ms 的视觉过渡把开抽往后推。 + ObserveTask(FadeInQuickDrawWindowAsync(window), "Quick draw notification fade-in failed."); + else if (window.Opacity < 1) window.Opacity = 1; - if (!window.IsVisible) - window.Show(); - ApplyQuickDrawWindowFocusFree(window); - Dispatcher.UIThread.Post( - () => PositionQuickDrawNotificationWindow(window, windowSettings), - DispatcherPriority.Render); - }).GetTask(); + + return window; + } + + private static void ApplyQuickDrawNotificationTheme(QuickDrawPageViewModel quickDraw, AdaptiveTheme theme) + { + _quickDrawNotificationTheme = theme; + quickDraw.ApplyNotificationTheme(theme); + } + + /// + /// 两个采样区是否基本重合:中心与尺寸都落在采样外扩量之内时,早先的采样结果仍然有效, + /// 不必为了一次 DPI 取整再抓一次屏。 + /// + private static bool IsCloseEnough(PixelRect left, PixelRect right) + { + var tolerance = NotificationBackdropSampleMarginPixels; + return Math.Abs(left.X + left.Width / 2 - (right.X + right.Width / 2)) <= tolerance + && Math.Abs(left.Y + left.Height / 2 - (right.Y + right.Height / 2)) <= tolerance + && Math.Abs(left.Width - right.Width) <= tolerance * 2 + && Math.Abs(left.Height - right.Height) <= tolerance * 2; + } + + /// + /// 在当前通知窗即将出现的位置采一块桌面亮度,换成白/黑前景方案。 + /// + /// + /// 采样失败(无平台实现、锁屏、远程桌面、区域被自己盖满)一律回退应用主题, + /// 绝不把"抓不到"当成"背景是黑的"。 + /// + private static async Task ResolveQuickDrawNotificationThemeAsync( + Window window, + NotificationChannelSettings settings, + Size? logicalSize = null) + { + var isDarkTheme = Application.Current?.ActualThemeVariant == ThemeVariant.Dark; + var fallback = AdaptiveBackdropResolver.FromAppTheme(isDarkTheme); + + // 关掉的开关与低配模式走同一条回退:不抓屏、不改配色,就是今天这个纯主题外观。 + // 低配模式强制关闭这一项,设置页因此把开关置灰并显示为关闭。 + if (!settings.AdaptiveForeground || Helpers.UiRenderQuality.IsLowSpecMode) + return fallback; + + var sampler = PlatformStartupContext.Current.ScreenLuminance; + if (!sampler.IsSupported) + return fallback; + + if (!TryResolveQuickDrawNotificationTargetRect( + window, settings, logicalSize, out var targetRect)) + return fallback; + + var region = new PlatformPixelRect( + targetRect.X - NotificationBackdropSampleMarginPixels, + targetRect.Y - NotificationBackdropSampleMarginPixels, + targetRect.Width + NotificationBackdropSampleMarginPixels * 2, + targetRect.Height + NotificationBackdropSampleMarginPixels * 2); + + // 只有窗口真的在画东西时才需要剔除自己:那时采到的会是上一轮通知的卡片,颜色会自我循环。 + // 以 Opacity=0 占位时整窗不显示任何像素,桌面是原样的,因此保留卡片区域反而更准。 + List exclusions = []; + if (window.IsVisible && window.Opacity > 0.01) + exclusions.Add(new PlatformPixelRect( + targetRect.X, targetRect.Y, targetRect.Width, targetRect.Height)); + + ScreenLuminanceSample? sample; + try + { + sample = await Task.Run(() => sampler.Sample(new ScreenLuminanceRequest(region, exclusions))) + .WaitAsync(NotificationBackdropSampleTimeout); + } + catch (TimeoutException) + { + return fallback; + } + catch (Exception ex) + { + IAppHost.TryGetService>()?.LogDebug(ex, "Quick draw notification backdrop sampling failed."); + return fallback; + } + + if (sample is null || sample.PixelCount < NotificationBackdropMinimumSamples) + return fallback; + + return AdaptiveBackdropResolver.Resolve( + BackdropLuminance.FromPercentiles(sample.P10, sample.Median, sample.P90), + isDarkTheme); + } + + private static async Task FadeInQuickDrawWindowAsync(Window window) + { + for (var step = 1; step <= NotificationFadeInSteps; step++) + { + if (!ReferenceEquals(window, _quickDrawWindow)) + return; + + window.Opacity = step / (double)NotificationFadeInSteps; + await Task.Delay(NotificationFadeInStepDelay); + } } public static void HideQuickDrawNotificationWindow() { Dispatcher.UIThread.Post(() => { + _quickDrawNotificationTheme = null; if (_quickDrawWindow is { IsVisible: true }) _quickDrawWindow.Hide(); }); @@ -2868,12 +2874,12 @@ private static async Task ShowQuickDrawNotificationWindowAsync( { _quickDrawNotificationSettings = windowSettings; var quickDraw = IAppHost.GetService(); - quickDraw.NotificationOpacity = Math.Clamp(windowSettings.Transparency, 20, 100); - var window = GetOrCreateQuickDrawWindow(); - window.Opacity = 1; - if (!window.IsVisible) - window.Show(); - ApplyQuickDrawWindowFocusFree(window); + + // 预览已经开始时窗口与主题都已就绪,这一步只是空转;没有预览的路径(例如只显示结果) + // 则在这里一次把建窗、定位、采样、淡入全部做完,保证 ShowNotificationPreview 写结果项之前 + // 前景色已经落定。 + var window = await PrepareQuickDrawNotificationWindowAsync(quickDraw, windowSettings); + if (showPreview) { quickDraw.ShowNotificationPreview(items, preserveQuickDrawResult); @@ -2886,7 +2892,7 @@ private static async Task ShowQuickDrawNotificationWindowAsync( DispatcherPriority.Render); } - private static async Task ShowQuickDrawWindowAsync() + private static async Task ShowQuickDrawWindowAsync(int count = 1) { TelemetryRuntimeService? telemetry = IAppHost.TryGetService(); using var transaction = telemetry?.StartTransaction("ui.quick_draw_window", "ui.navigation"); @@ -2974,6 +2980,7 @@ private static Window GetOrCreateQuickDrawWindow() quickDrawPage.ResultLayoutChanged -= resultLayoutChanged; _quickDrawWindow = null; _quickDrawNotificationSettings = null; + _quickDrawNotificationTheme = null; }; return _quickDrawWindow; } @@ -3042,30 +3049,41 @@ private static void PositionQuickDrawNotificationWindow( if (window is null) return; - var nativeNames = WindowsMonitorNameProvider.GetNames(); - var screen = window.Screens.All.FirstOrDefault(candidate => - { - nativeNames.TryGetValue(candidate.Bounds.Position, out var nativeName); - var displayName = string.IsNullOrWhiteSpace(candidate.DisplayName) - ? nativeName - : candidate.DisplayName; - return !string.IsNullOrWhiteSpace(settings.EnabledMonitor) - && NotificationMonitorIdentifier.Matches( - displayName, - candidate.Bounds, - settings.EnabledMonitor); - }) - ?? window.Screens.Primary - ?? window.Screens.All.FirstOrDefault(); - if (screen is null) + if (!TryResolveQuickDrawNotificationTargetRect(window, settings, logicalSize, out var target)) return; + if (window.Position != target.Position) + window.Position = target.Position; + } + + /// + /// 算出通知窗最终会出现在哪里、多大:定位与背景采样共用这一份结果。 + /// + /// + /// 两边各算一次是不行的——缩放取整或 working-area 夹取上的任何一点差异,都会让采样区 + /// 偏到卡片旁边,白/黑前景就会按错的桌面亮度决定。 + /// + private static bool TryResolveQuickDrawNotificationTargetRect( + Window window, + NotificationChannelSettings settings, + Size? logicalSize, + out PixelRect target) + { + target = default; + + var screen = ResolveQuickDrawNotificationScreen(window, settings); + if (screen is null) + return false; + var scale = window.RenderScaling; var size = logicalSize ?? window.Bounds.Size; + if (size.Width <= 0 || size.Height <= 0) + size = new Size(window.MinWidth, window.MinHeight); + var width = (int)Math.Round(size.Width * scale); var height = (int)Math.Round(size.Height * scale); if (width <= 0 || height <= 0) - return; + return false; var area = screen.WorkingArea; var x = settings.WindowPosition switch @@ -3082,11 +3100,31 @@ private static void PositionQuickDrawNotificationWindow( 3 or 4 => area.Center.Y - height / 2, _ => area.Center.Y - height / 2 }; - var target = new PixelPoint( + target = new PixelRect( Math.Clamp(x + settings.HorizontalOffset, area.X, Math.Max(area.X, area.Right - width)), - Math.Clamp(y + settings.VerticalOffset, area.Y, Math.Max(area.Y, area.Bottom - height))); - if (window.Position != target) - window.Position = target; + Math.Clamp(y + settings.VerticalOffset, area.Y, Math.Max(area.Y, area.Bottom - height)), + width, + height); + return true; + } + + private static Screen? ResolveQuickDrawNotificationScreen(Window window, NotificationChannelSettings settings) + { + var nativeNames = WindowsMonitorNameProvider.GetNames(); + return window.Screens.All.FirstOrDefault(candidate => + { + nativeNames.TryGetValue(candidate.Bounds.Position, out var nativeName); + var displayName = string.IsNullOrWhiteSpace(candidate.DisplayName) + ? nativeName + : candidate.DisplayName; + return !string.IsNullOrWhiteSpace(settings.EnabledMonitor) + && NotificationMonitorIdentifier.Matches( + displayName, + candidate.Bounds, + settings.EnabledMonitor); + }) + ?? window.Screens.Primary + ?? window.Screens.All.FirstOrDefault(); } private static void ApplyQuickDrawWindowBounds(Window? window) diff --git a/SecRandom/Langs/SettingsPages/General/Backup/Resources.Designer.cs b/SecRandom/Langs/SettingsPages/General/Backup/Resources.Designer.cs index ae73dab68..83a498f47 100644 --- a/SecRandom/Langs/SettingsPages/General/Backup/Resources.Designer.cs +++ b/SecRandom/Langs/SettingsPages/General/Backup/Resources.Designer.cs @@ -562,644 +562,5 @@ public static string S_RestoreBackup { return ResourceManager.GetString("S_RestoreBackup", resourceCulture); } } - - /// - /// Looks up a localized string similar to 不完整. - /// - public static string C_CloudBackup_Incomplete { - get { - return ResourceManager.GetString("C_CloudBackup_Incomplete", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 备份. - /// - public static string C_CloudBackup_Backups_FileName { - get { - return ResourceManager.GetString("C_CloudBackup_Backups_FileName", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 上传时间. - /// - public static string C_CloudBackup_Backups_DateTime { - get { - return ResourceManager.GetString("C_CloudBackup_Backups_DateTime", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 操作. - /// - public static string C_CloudBackup_Backups_Operations { - get { - return ResourceManager.GetString("C_CloudBackup_Backups_Operations", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 下载恢复. - /// - public static string C_CloudBackup_Backups_Restore { - get { - return ResourceManager.GetString("C_CloudBackup_Backups_Restore", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 大小. - /// - public static string C_CloudBackup_Backups_Size { - get { - return ResourceManager.GetString("C_CloudBackup_Backups_Size", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 取消上传. - /// - public static string C_CloudBackup_Cancel { - get { - return ResourceManager.GetString("C_CloudBackup_Cancel", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 清理不完整备份. - /// - public static string C_CloudBackup_Cleanup { - get { - return ResourceManager.GetString("C_CloudBackup_Cleanup", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 未登录. - /// - public static string C_CloudBackup_NotSignedIn { - get { - return ResourceManager.GetString("C_CloudBackup_NotSignedIn", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to {0} / {1}(本应用 {2}). - /// - public static string C_CloudBackup_QuotaUsage { - get { - return ResourceManager.GetString("C_CloudBackup_QuotaUsage", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 刷新云端空间用量. - /// - public static string C_CloudBackup_QuotaRefresh { - get { - return ResourceManager.GetString("C_CloudBackup_QuotaRefresh", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 刷新云端备份. - /// - public static string C_CloudBackup_Refresh { - get { - return ResourceManager.GetString("C_CloudBackup_Refresh", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 登录账号. - /// - public static string C_CloudBackup_SignIn { - get { - return ResourceManager.GetString("C_CloudBackup_SignIn", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to {0}. - /// - public static string C_CloudBackup_SignedInAs { - get { - return ResourceManager.GetString("C_CloudBackup_SignedInAs", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 开始上传. - /// - public static string C_CloudBackup_Upload { - get { - return ResourceManager.GetString("C_CloudBackup_Upload", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 云端备份. - /// - public static string C_Tab_CloudBackup { - get { - return ResourceManager.GetString("C_Tab_CloudBackup", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 本地备份. - /// - public static string C_Tab_LocalBackup { - get { - return ResourceManager.GetString("C_Tab_LocalBackup", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 清理不完整备份失败. - /// - public static string M_CloudCleanupFailed { - get { - return ResourceManager.GetString("M_CloudCleanupFailed", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 已清理 {0} 份不完整备份. - /// - public static string M_CloudCleanupSuccess { - get { - return ResourceManager.GetString("M_CloudCleanupSuccess", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 确定要删除云端备份“{0}”吗?此操作无法撤销. - /// - public static string M_CloudDeleteContent { - get { - return ResourceManager.GetString("M_CloudDeleteContent", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 删除云端备份失败. - /// - public static string M_CloudDeleteFailed { - get { - return ResourceManager.GetString("M_CloudDeleteFailed", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 已删除云端备份. - /// - public static string M_CloudDeleteSuccess { - get { - return ResourceManager.GetString("M_CloudDeleteSuccess", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 删除云端备份. - /// - public static string M_CloudDeleteTitle { - get { - return ResourceManager.GetString("M_CloudDeleteTitle", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 云端备份下载失败. - /// - public static string M_CloudDownloadFailed { - get { - return ResourceManager.GetString("M_CloudDownloadFailed", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 该云端备份不完整,无法恢复. - /// - public static string M_CloudIncomplete { - get { - return ResourceManager.GetString("M_CloudIncomplete", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 清理中ing~. - /// - public static string M_CloudCleaning { - get { - return ResourceManager.GetString("M_CloudCleaning", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 云空间不足,请清理云端备份后重试. - /// - public static string M_CloudQuotaExceeded { - get { - return ResourceManager.GetString("M_CloudQuotaExceeded", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 正在获取. - /// - public static string M_CloudQuotaLoading { - get { - return ResourceManager.GetString("M_CloudQuotaLoading", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 无法获取云端空间用量. - /// - public static string M_CloudQuotaUnknown { - get { - return ResourceManager.GetString("M_CloudQuotaUnknown", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 无法打开云储存页面. - /// - public static string M_CloudStoragePageFailed { - get { - return ResourceManager.GetString("M_CloudStoragePageFailed", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 刷新中ing~. - /// - public static string M_CloudRefreshing { - get { - return ResourceManager.GetString("M_CloudRefreshing", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 获取云端备份列表失败. - /// - public static string M_CloudRefreshFailed { - get { - return ResourceManager.GetString("M_CloudRefreshFailed", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 恢复云端备份“{0}”会覆盖当前对应数据;恢复前会自动创建一份当前数据快照,恢复完成后需要重启应用. - /// - public static string M_CloudRestoreContent { - get { - return ResourceManager.GetString("M_CloudRestoreContent", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 恢复云端备份失败. - /// - public static string M_CloudRestoreFailed { - get { - return ResourceManager.GetString("M_CloudRestoreFailed", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 云端备份已恢复,请重启应用后生效. - /// - public static string M_CloudRestoreSuccess { - get { - return ResourceManager.GetString("M_CloudRestoreSuccess", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 从云端恢复. - /// - public static string M_CloudRestoreTitle { - get { - return ResourceManager.GetString("M_CloudRestoreTitle", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to SECTL 尚未为该应用启用云服务. - /// - public static string M_CloudServiceDisabled { - get { - return ResourceManager.GetString("M_CloudServiceDisabled", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 请先登录 SECTL 账号. - /// - public static string M_CloudSignInRequired { - get { - return ResourceManager.GetString("M_CloudSignInRequired", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to SECTL 登录状态已失效,请重新登录. - /// - public static string M_CloudSignedOut { - get { - return ResourceManager.GetString("M_CloudSignedOut", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 云端备份上传已取消. - /// - public static string M_CloudUploadCancelled { - get { - return ResourceManager.GetString("M_CloudUploadCancelled", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 上传中ing~. - /// - public static string M_CloudUploading { - get { - return ResourceManager.GetString("M_CloudUploading", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 云端备份上传失败. - /// - public static string M_CloudUploadFailed { - get { - return ResourceManager.GetString("M_CloudUploadFailed", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 云端备份上传完成. - /// - public static string M_CloudUploadSuccess { - get { - return ResourceManager.GetString("M_CloudUploadSuccess", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 云端服务响应超时,可能是服务端负载过高,请稍后重试. - /// - public static string M_CloudServerTimeout { - get { - return ResourceManager.GetString("M_CloudServerTimeout", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 云端服务暂时不可用,请稍后重试. - /// - public static string M_CloudServerError { - get { - return ResourceManager.GetString("M_CloudServerError", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 若云端残留未完成的分片,可使用“清理不完整备份”移除. - /// - public static string M_CloudUploadCleanupHint { - get { - return ResourceManager.GetString("M_CloudUploadCleanupHint", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 云端备份. - /// - public static string S_CloudBackup { - get { - return ResourceManager.GetString("S_CloudBackup", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 账号状态. - /// - public static string S_CloudBackup_Account { - get { - return ResourceManager.GetString("S_CloudBackup_Account", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 当前用于云同步的 SECTL 账号. - /// - public static string S_CloudBackup_Account_D { - get { - return ResourceManager.GetString("S_CloudBackup_Account_D", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 登录 SECTL 账号后可将数据备份上传到云端并随时恢复. - /// - public static string S_CloudBackup_D { - get { - return ResourceManager.GetString("S_CloudBackup_D", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 云端备份管理. - /// - public static string S_CloudBackup_List { - get { - return ResourceManager.GetString("S_CloudBackup_List", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 已上传的云端备份,可下载恢复或删除. - /// - public static string S_CloudBackup_List_D { - get { - return ResourceManager.GetString("S_CloudBackup_List_D", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 选择需要包含在备份文件中的数据. - /// - public static string S_CloudIncludes_D { - get { - return ResourceManager.GetString("S_CloudIncludes_D", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 设备别名. - /// - public static string S_CloudDeviceAlias { - get { - return ResourceManager.GetString("S_CloudDeviceAlias", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 用于区分不同设备的云端备份,会显示在云端文件名中;留空则使用本机名称. - /// - public static string S_CloudDeviceAlias_D { - get { - return ResourceManager.GetString("S_CloudDeviceAlias_D", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 云端备份内容. - /// - public static string S_CloudIncludes { - get { - return ResourceManager.GetString("S_CloudIncludes", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 云端自动备份. - /// - public static string S_CloudAutoBackup { - get { - return ResourceManager.GetString("S_CloudAutoBackup", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 按设定的间隔自动备份到云端,云空间不足时会删除整个账号最早的云端备份. - /// - public static string S_CloudAutoBackup_D { - get { - return ResourceManager.GetString("S_CloudAutoBackup_D", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 自动备份间隔. - /// - public static string S_CloudAutoBackup_IntervalDays { - get { - return ResourceManager.GetString("S_CloudAutoBackup_IntervalDays", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 设置云端自动备份间隔(天). - /// - public static string S_CloudAutoBackup_IntervalDays_D { - get { - return ResourceManager.GetString("S_CloudAutoBackup_IntervalDays_D", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 自动备份上限. - /// - public static string S_CloudAutoBackup_MaxCount { - get { - return ResourceManager.GetString("S_CloudAutoBackup_MaxCount", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 设置本设备在云端最多保留的备份数量(个),0为不限制,超出后自动删除本设备最早的备份. - /// - public static string S_CloudAutoBackup_MaxCount_D { - get { - return ResourceManager.GetString("S_CloudAutoBackup_MaxCount_D", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 云端空间. - /// - public static string S_CloudBackup_Quota { - get { - return ResourceManager.GetString("S_CloudBackup_Quota", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 当前账号的云空间用量与本应用占用. - /// - public static string S_CloudBackup_Quota_D { - get { - return ResourceManager.GetString("S_CloudBackup_Quota_D", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 用量. - /// - public static string S_CloudBackup_Quota_R { - get { - return ResourceManager.GetString("S_CloudBackup_Quota_R", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 打开 思拓创联 云储存页面. - /// - public static string S_CloudBackup_OpenStoragePage { - get { - return ResourceManager.GetString("S_CloudBackup_OpenStoragePage", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 在浏览器中打开 SECTL 云储存网页,查看与管理云端文件. - /// - public static string S_CloudBackup_OpenStoragePage_D { - get { - return ResourceManager.GetString("S_CloudBackup_OpenStoragePage_D", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 立即备份到云端. - /// - public static string S_CloudBackup_Upload { - get { - return ResourceManager.GetString("S_CloudBackup_Upload", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 将所选数据打包上传到云端. - /// - public static string S_CloudBackup_Upload_D { - get { - return ResourceManager.GetString("S_CloudBackup_Upload_D", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 旧版加密,无法恢复. - /// - public static string C_CloudBackup_LegacyEncrypted { - get { - return ResourceManager.GetString("C_CloudBackup_LegacyEncrypted", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 该备份由旧版本以加密口令上传,当前版本已移除加密功能,无法恢复它. - /// - public static string M_CloudLegacyEncrypted { - get { - return ResourceManager.GetString("M_CloudLegacyEncrypted", resourceCulture); - } - } } } diff --git a/SecRandom/Langs/SettingsPages/General/Backup/Resources.en-US.resx b/SecRandom/Langs/SettingsPages/General/Backup/Resources.en-US.resx index 14be91ab6..b7de93e58 100644 --- a/SecRandom/Langs/SettingsPages/General/Backup/Resources.en-US.resx +++ b/SecRandom/Langs/SettingsPages/General/Backup/Resources.en-US.resx @@ -1 +1 @@ -Automatic backup intervalSet the automatic backup interval in daysAutomatic backup limitSet the maximum number of automatic backups to keep; 0 means unlimitedAutomatic BackupBackup contentsConfiguration filesList dataHistoryDraw proof filesAudio resourcesCSES linkageImage resourcesRuntime logsSelect the data to include in the backupApplication settings and configuration files (config)Audio resource files (audio)CSES linkage data (CSES)Draw history data (history)Proof files for reproducing and verifying draw results (proofs)Member and prize image resources (images)Roll-call and lottery list data (list)Application logs, which may contain sensitive information (logs)Enable automatic backupsView backup filesOpen the backup folderBackup storage usageSpace used by the backup folderBack up nowCreate a full backup immediatelySpace usedRestore backupRefresh backupsFile nameCreatedSizeActionsRestoreDeleteCancelCloseBackup created: {0}Backup failedBackup file not found. Refresh and try againDelete backup “{0}”? This cannot be undoneUnable to delete backupDeleteBackup deletedDelete BackupThe backup contains an invalid path; restore cancelledSelect at least one type of backup contentRestoring “{0}” will overwrite the corresponding current data. A snapshot is created before restore; restart the application when it finishesBackup restore failedRestoreBackup restored. Restart the application to apply itRestore BackupCloud backupSign in to your SECTL account to upload data backups to the cloud and restore them anytimeAccount statusThe SECTL account currently used for cloud syncCloud storageCloud storage usage for the account and for this applicationUsageOpen the SECTL cloud storage pageOpen the SECTL cloud storage page in your browser to view and manage cloud filesBack up to the cloud nowPackages the selected data and uploads it to the cloudCloud backup contentsSelect the data to include in the backupDevice aliasDistinguishes this device's cloud backups and appears in the cloud file names; leave empty to use this computer's nameAutomatic cloud backupBacks up to the cloud on the configured interval and removes the oldest cloud backup of the whole account when the space runs outAutomatic backup intervalSet the automatic cloud backup interval in daysAutomatic backup limitSet how many of this device's cloud backups to keep; 0 means unlimited and this device's older backups are removed automaticallyCloud backup managementUploaded cloud backups that can be downloaded, restored, or deletedSign inStart uploadCancel uploadRefresh cloud backupsClean up incomplete backupsNot signed inRefresh cloud storage usageLocal backupCloud backup{0}IncompleteBackup{0} / {1} (this app {2})UploadedSizeActionsDownload and restoreSign in to your SECTL account firstUploading~Refreshing~Cleaning~FetchingCloud backup uploadedCloud backup upload failedThe cloud service timed out; the server may be overloaded, so try again laterThe cloud service is temporarily unavailable; try again laterIf incomplete parts remain in the cloud, use “Clean up incomplete backups” to remove themCloud backup upload cancelledFailed to load cloud backupsDelete cloud backupDelete cloud backup “{0}”? This cannot be undoneCloud backup deletedFailed to delete the cloud backupRestore from cloudRestoring cloud backup “{0}” overwrites the corresponding current data. A snapshot is created before restore; restart the application when it finishesCloud backup restored. Restart the application to apply itCloud backup restore failedCloud backup download failedThis cloud backup is incomplete and cannot be restoredCloud storage is full; free some space and try againSECTL has not enabled the cloud service for this applicationYour SECTL sign-in has expired; sign in againRemoved {0} incomplete backupsFailed to clean up incomplete backupsCloud storage usage is unavailableCould not open the cloud storage pageLegacy encrypted, cannot restoreThis backup was uploaded by an older version with an encryption passphrase; encryption has been removed, so this version cannot restore it +Automatic backup intervalSet the automatic backup interval in daysAutomatic backup limitSet the maximum number of automatic backups to keep; 0 means unlimitedAutomatic BackupBackup contentsConfiguration filesList dataHistoryDraw proof filesAudio resourcesCSES linkageImage resourcesRuntime logsSelect the data to include in the backupApplication settings and configuration files (config)Audio resource files (audio)CSES linkage data (CSES)Draw history data (history)Proof files for reproducing and verifying draw results (proofs)Member and prize image resources (images)Roll-call and lottery list data (list)Application logs, which may contain sensitive information (logs)Enable automatic backupsView backup filesOpen the backup folderBackup storage usageSpace used by the backup folderBack up nowCreate a full backup immediatelySpace usedRestore backupRefresh backupsFile nameCreatedSizeActionsRestoreDeleteCancelCloseBackup created: {0}Backup failedBackup file not found. Refresh and try againDelete backup “{0}”? This cannot be undoneUnable to delete backupDeleteBackup deletedDelete BackupThe backup contains an invalid path; restore cancelledSelect at least one type of backup contentRestoring “{0}” will overwrite the corresponding current data. A snapshot is created before restore; restart the application when it finishesBackup restore failedRestoreBackup restored. Restart the application to apply itRestore Backup diff --git a/SecRandom/Langs/SettingsPages/General/Backup/Resources.ja-JP.resx b/SecRandom/Langs/SettingsPages/General/Backup/Resources.ja-JP.resx index ec72969d2..60a2a26ec 100644 --- a/SecRandom/Langs/SettingsPages/General/Backup/Resources.ja-JP.resx +++ b/SecRandom/Langs/SettingsPages/General/Backup/Resources.ja-JP.resx @@ -1 +1 @@ -自動バックアップ間隔自動バックアップの間隔(日)を設定します自動バックアップ上限保持する自動バックアップの最大数を設定し、0 は無制限自動バックアップバックアップ内容設定ファイルリストデータ履歴抽選証明ファイル音声リソースCSES 連携画像リソース実行ログバックアップに含めるデータを選択しますアプリ設定と構成ファイル(config)音声リソースファイル(audio)CSES 連携データ(CSES)抽選履歴データ(history)抽選結果の再現と検証に使う証明ファイル(proofs)メンバー・賞品の画像リソース(images)点呼・抽選リストなどのデータ(list)機密情報を含む可能性がある実行ログ(logs)自動バックアップを有効にしますバックアップファイルを表示バックアップフォルダーを開きますバックアップ使用量バックアップフォルダーの使用容量今すぐバックアップ完全バックアップをすぐに作成します使用容量バックアップを復元バックアップを更新ファイル名作成日時サイズ操作復元削除キャンセル閉じるバックアップを作成しました: {0}バックアップに失敗しましたバックアップファイルがありません。更新して再試行してくださいバックアップ「{0}」を削除しますか?元に戻せませんバックアップを削除できませんでした削除バックアップを削除しましたバックアップを削除バックアップに無効なパスが含まれるため、復元をキャンセルしましたバックアップ内容を1つ以上選択してください「{0}」を復元すると現在の対応データが上書きされます。復元前にスナップショットを作成し、完了後はアプリを再起動してくださいバックアップの復元に失敗しました復元バックアップを復元しました。反映するにはアプリを再起動してくださいバックアップを復元クラウドバックアップSECTL アカウントにサインインすると、データバックアップをクラウドへアップロードしていつでも復元できますアカウント状態クラウド同期に使用中の SECTL アカウントクラウド容量アカウント全体と本アプリのクラウド使用量使用量SECTL クラウドストレージのページを開くブラウザーで SECTL クラウドストレージのページを開き、クラウド上のファイルを確認・管理します今すぐクラウドへバックアップ選択したデータをまとめてクラウドへアップロードしますクラウドバックアップ内容バックアップに含めるデータを選択しますデバイス名デバイスごとにクラウドバックアップを区別するための名前で、クラウド上のファイル名に表示され、空欄の場合はこのコンピューターの名前を使用しますクラウド自動バックアップ設定した間隔でクラウドへ自動バックアップし、容量が不足するとアカウント全体で最も古いクラウドバックアップを削除します自動バックアップ間隔クラウド自動バックアップの間隔(日)を設定します自動バックアップ上限このデバイスがクラウドに保持するバックアップの最大数を設定し、0 は無制限、超過分はこのデバイスの古いものから自動削除しますクラウドバックアップ管理アップロード済みのクラウドバックアップ(ダウンロードして復元、または削除できます)サインインアップロード開始アップロードを中止クラウドバックアップを更新不完全なバックアップを整理未サインインクラウド容量の使用量を更新ローカルバックアップクラウドバックアップ{0}不完全{0} / {1}(本アプリ {2})バックアップアップロード日時サイズ操作ダウンロードして復元先に SECTL アカウントへサインインしてくださいアップロード中ing~更新中ing~整理中ing~取得中クラウドバックアップのアップロードが完了しましたクラウドバックアップのアップロードに失敗しましたクラウドサービスがタイムアウトしました。サーバー負荷が高い可能性があるため、しばらくして再試行してくださいクラウドサービスが一時的に利用できません。しばらくして再試行してくださいクラウドに未完了のパートが残っている場合は「不完全なバックアップを整理」で削除できますクラウドバックアップのアップロードを中止しましたクラウドバックアップ一覧の取得に失敗しましたクラウドバックアップを削除クラウドバックアップ「{0}」を削除しますか?この操作は取り消せませんクラウドバックアップを削除しましたクラウドバックアップの削除に失敗しましたクラウドから復元クラウドバックアップ「{0}」を復元すると現在の対応データが上書きされます。復元前にスナップショットを自動作成し、完了後はアプリの再起動が必要ですクラウドバックアップを復元しました。再起動後に反映されますクラウドバックアップの復元に失敗しましたクラウドバックアップのダウンロードに失敗しましたこのクラウドバックアップは不完全なため復元できませんクラウド容量が不足しています。バックアップを整理して再試行してくださいSECTL 側でこのアプリのクラウドサービスが有効になっていませんSECTL のサインインが無効になりました。再度サインインしてください不完全なバックアップを {0} 件整理しました不完全なバックアップの整理に失敗しましたクラウド使用量を取得できませんクラウドストレージのページを開けませんでした旧版暗号化、復元不可このバックアップは旧バージョンが暗号化パスフレーズでアップロードしたもので、現行バージョンでは暗号化機能を削除したため復元できません +自動バックアップ間隔自動バックアップの間隔(日)を設定します自動バックアップ上限保持する自動バックアップの最大数を設定し、0 は無制限自動バックアップバックアップ内容設定ファイルリストデータ履歴抽選証明ファイル音声リソースCSES 連携画像リソース実行ログバックアップに含めるデータを選択しますアプリ設定と構成ファイル(config)音声リソースファイル(audio)CSES 連携データ(CSES)抽選履歴データ(history)抽選結果の再現と検証に使う証明ファイル(proofs)メンバー・賞品の画像リソース(images)点呼・抽選リストなどのデータ(list)機密情報を含む可能性がある実行ログ(logs)自動バックアップを有効にしますバックアップファイルを表示バックアップフォルダーを開きますバックアップ使用量バックアップフォルダーの使用容量今すぐバックアップ完全バックアップをすぐに作成します使用容量バックアップを復元バックアップを更新ファイル名作成日時サイズ操作復元削除キャンセル閉じるバックアップを作成しました: {0}バックアップに失敗しましたバックアップファイルがありません。更新して再試行してくださいバックアップ「{0}」を削除しますか?元に戻せませんバックアップを削除できませんでした削除バックアップを削除しましたバックアップを削除バックアップに無効なパスが含まれるため、復元をキャンセルしましたバックアップ内容を1つ以上選択してください「{0}」を復元すると現在の対応データが上書きされます。復元前にスナップショットを作成し、完了後はアプリを再起動してくださいバックアップの復元に失敗しました復元バックアップを復元しました。反映するにはアプリを再起動してくださいバックアップを復元 diff --git a/SecRandom/Langs/SettingsPages/General/Backup/Resources.resx b/SecRandom/Langs/SettingsPages/General/Backup/Resources.resx index 77ed269c7..66edb634d 100644 --- a/SecRandom/Langs/SettingsPages/General/Backup/Resources.resx +++ b/SecRandom/Langs/SettingsPages/General/Backup/Resources.resx @@ -192,217 +192,75 @@ 恢复备份 - - 云端备份 - - - 登录 SECTL 账号后可将数据备份上传到云端并随时恢复 - - - 账号状态 - - - 当前用于云同步的 SECTL 账号 - - - 云端空间 - - - 当前账号的云空间用量与本应用占用 - - - 用量 - - - 打开 思拓创联 云储存页面 - - - 在浏览器中打开 SECTL 云储存网页,查看与管理云端文件 - - - 立即备份到云端 - - - 将所选数据打包上传到云端 - - - 云端备份内容 - - - 选择需要包含在备份文件中的数据 - - - 设备别名 - - - 用于区分不同设备的云端备份,会显示在云端文件名中;留空则使用本机名称 - - - 云端自动备份 - - - 按设定的间隔自动备份到云端,云空间不足时会删除整个账号最早的云端备份 - - - 自动备份间隔 - - - 设置云端自动备份间隔(天) - - - 自动备份上限 - - - 设置本设备在云端最多保留的备份数量(个),0为不限制,超出后自动删除本设备最早的备份 - - - 云端备份管理 - - - 已上传的云端备份,可下载恢复或删除 - - - 登录账号 - - - 开始上传 - - - 取消上传 - - - 刷新云端备份 - - - 清理不完整备份 - - - 未登录 - - - 刷新云端空间用量 - - - 本地备份 - - - 云端备份 - - - {0} / {1}(本应用 {2}) - - - {0} - - - 不完整 - - - 备份 - - - 上传时间 - - - 大小 - - - 操作 - - - 下载恢复 - - - 请先登录 SECTL 账号 - - - 上传中ing~ - - - 刷新中ing~ - - - 清理中ing~ - - - 正在获取 - - - 云端备份上传完成 - - - 云端备份上传失败 - - - 云端服务响应超时,可能是服务端负载过高,请稍后重试 - - - 云端服务暂时不可用,请稍后重试 - - - 若云端残留未完成的分片,可使用“清理不完整备份”移除 - - - 云端备份上传已取消 - - - 获取云端备份列表失败 - - - 删除云端备份 - - - 确定要删除云端备份“{0}”吗?此操作无法撤销 - - - 已删除云端备份 - - - 删除云端备份失败 - - - 从云端恢复 - - - 恢复云端备份“{0}”会覆盖当前对应数据;恢复前会自动创建一份当前数据快照,恢复完成后需要重启应用 - - - 云端备份已恢复,请重启应用后生效 - - - 恢复云端备份失败 - - - 云端备份下载失败 - - - 该云端备份不完整,无法恢复 - - - 云空间不足,请清理云端备份后重试 - - - SECTL 尚未为该应用启用云服务 - - - SECTL 登录状态已失效,请重新登录 - - - 已清理 {0} 份不完整备份 - - - 清理不完整备份失败 - - - 无法获取云端空间用量 - - - 无法打开云储存页面 - - - 旧版加密,无法恢复 - - - 该备份由旧版本以加密口令上传,当前版本已移除加密功能,无法恢复它 - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/SecRandom/Langs/SettingsPages/General/Verification/Resources.Designer.cs b/SecRandom/Langs/SettingsPages/General/Verification/Resources.Designer.cs index 8e3c5f989..0649d1759 100644 --- a/SecRandom/Langs/SettingsPages/General/Verification/Resources.Designer.cs +++ b/SecRandom/Langs/SettingsPages/General/Verification/Resources.Designer.cs @@ -58,20 +58,4 @@ public class Resources public static string M_ProofQueueFailed => Get(nameof(M_ProofQueueFailed)); public static string M_ProofQueueConflict => Get(nameof(M_ProofQueueConflict)); public static string M_ProofQueueTimestampFailed => Get(nameof(M_ProofQueueTimestampFailed)); - public static string M_ProofQueueChainAlert => Get(nameof(M_ProofQueueChainAlert)); - public static string S_ProofIntegrity => Get(nameof(S_ProofIntegrity)); - public static string S_ProofIntegrity_D => Get(nameof(S_ProofIntegrity_D)); - public static string C_VerifyProofs => Get(nameof(C_VerifyProofs)); - public static string M_ProofIntegrityIdle => Get(nameof(M_ProofIntegrityIdle)); - public static string M_ProofIntegrityHealthy => Get(nameof(M_ProofIntegrityHealthy)); - public static string M_ProofIntegrityCounts => Get(nameof(M_ProofIntegrityCounts)); - public static string M_ProofIntegrityProblems => Get(nameof(M_ProofIntegrityProblems)); - public static string M_ProofIntegrityLimits => Get(nameof(M_ProofIntegrityLimits)); - public static string M_ProofIssue_Unreadable => Get(nameof(M_ProofIssue_Unreadable)); - public static string M_ProofIssue_Modified => Get(nameof(M_ProofIssue_Modified)); - public static string M_ProofIssue_UnsupportedVersion => Get(nameof(M_ProofIssue_UnsupportedVersion)); - public static string M_ProofIssue_BrokenLink => Get(nameof(M_ProofIssue_BrokenLink)); - public static string M_ProofIssue_Gap => Get(nameof(M_ProofIssue_Gap)); - public static string M_ProofIssue_BeyondHead => Get(nameof(M_ProofIssue_BeyondHead)); - public static string M_ProofIssue_MissingTail => Get(nameof(M_ProofIssue_MissingTail)); } diff --git a/SecRandom/Langs/SettingsPages/General/Verification/Resources.en-US.resx b/SecRandom/Langs/SettingsPages/General/Verification/Resources.en-US.resx index 8bc11a81a..f5e1b4434 100644 --- a/SecRandom/Langs/SettingsPages/General/Verification/Resources.en-US.resx +++ b/SecRandom/Langs/SettingsPages/General/Verification/Resources.en-US.resx @@ -1,6 +1,4 @@ -Draw VerificationVerifiable DrawsServer VerificationOrdinary mode draws locally immediately, works offline, and saves a locally replayable proof. When online, new proofs are submitted for server replay verification in the background and a third-party time stamp is requested (the proof digest only — never the roster or draw content). Historical proofs are not uploaded automatically; you can upload them manually on the verification website. Proofs form an append-only hash chain, so later edits, deleted proofs, and a wiped-and-rebuilt chain are all detectable, and each proof commits a digest of the record-id-to-name mapping of the roster it used, so editing the list afterwards is detectable too. It does not prove that the local program, random seed, or roster was unchanged before the draw, nor rule out filtering the roster before drawingVerifiable draw modeOrdinary mode draws locally while offline and can be verified manually later; formal notarization has the server lock the candidate pool, generate random material, and calculate the final resultOrdinary modeFormal notarizationSwitch Verifiable Draw ModeI have read this and want to switchCancelI have read and understood the limitations aboveOrdinary mode draws locally immediately, works offline, and saves a replayable proof. When online, the app submits one replay-signing request to fair.sectl.cn in the background only for each newly completed ordinary draw and requests a third-party time stamp (the proof digest only — never the roster or draw content). Offline or failed historical proofs are not uploaded automatically. - -Proofs form an append-only hash chain, so later edits, deleted proofs, and a wiped-and-rebuilt chain are detectable; the service also remembers the chain head it has seen for each device, so rebuilding after deleting the local proofs is reported as a backwards chain position. +Draw VerificationVerifiable DrawsServer VerificationOrdinary mode draws locally immediately, works offline, and saves a locally replayable proof. When online, new proofs are submitted for server replay verification in the background and a third-party time stamp is requested (the proof digest only — never the roster or draw content). Historical proofs are not uploaded automatically; you can upload them manually on the verification website. Each proof commits a digest of the record-id-to-name mapping of the roster it used, so editing the list afterwards is detectable too. It does not prove that the local program, random seed, or roster was unchanged before the draw, nor rule out filtering the roster before drawingVerifiable draw modeOrdinary mode draws locally while offline and can be verified manually later; formal notarization has the server lock the candidate pool, generate random material, and calculate the final resultOrdinary modeFormal notarizationSwitch Verifiable Draw ModeI have read this and want to switchCancelI have read and understood the limitations aboveOrdinary mode draws locally immediately, works offline, and saves a replayable proof. When online, the app submits one replay-signing request to fair.sectl.cn in the background only for each newly completed ordinary draw and requests a third-party time stamp (the proof digest only — never the roster or draw content). Offline or failed historical proofs are not uploaded automatically. Each proof commits a digest of the "record id to name/number/group" mapping of the roster it used, so editing the list afterwards to point a winning record at someone else is detectable. @@ -8,4 +6,4 @@ It cannot prove that the local program, real roster, or random seed was unchange If network instability, disconnection, service unavailability, device failure, or force majeure prevents a completed server proof, no local substitute is generated and ordinary mode is not used automatically. After the server confirms the lock, the candidate pool, weights, rules, random material, and result cannot be replaced, supplemented, or recalculated in the same flow. A new draw is a separate notarization. -This prevents replacement of local draw code, random seeds, or result files during the locked flow, but cannot prove that the real roster is complete and authentic or that the pool was not manually filtered before submissionDraw proof filesProofs are saved by date automatically; open the folder to upload .srproof.json files to the verification websiteOpen proof folderOpen verification websiteLocal proof storage limitAfter each new proof, the oldest proof files are deleted when this limit is exceeded; 64 MB by default16 MB32 MB64 MB128 MB256 MB512 MB1 GBLocal proof retentionOnly local .srproof.json files are cleaned; shared website links are not affected; expired files are removed when the next proof is generated7 days15 days30 days60 days90 daysNever clearDraw VerificationServer replay verification succeeded; the proof was savedThe server is temporarily unavailable. A locally replayable proof was saved; you can upload it to the verification website laterProof submission queueOrdinary-mode proofs are saved immediately and submitted for server replay verification in the background, failures are retried automatically, and submission resumes after reconnecting or restartingRetry nowAll proofs have been submitted for server verification{0} awaiting submission{0} failed{0} proof files changed during submissionProof chain integrityChecks whether the local proof hash chain is continuous and unmodified; the local chain only makes deletion and edits visible, it cannot prove that no earlier record was removedVerify nowNot verified yetProof chain is intact{0} proofs, {1} chained, {2} in the legacy formatgaps {0}, broken links {1}, modified {2}, beyond head {3}, not written {4}, expired {5}The local chain only makes deletion and edits visible, it cannot prove that no earlier record was removedunreadablemodifiedunsupported versionlink mismatchmissing filebeyond chain headnot written{0} awaiting time stamp{0} chain mismatches reported by the service +This prevents replacement of local draw code, random seeds, or result files during the locked flow, but cannot prove that the real roster is complete and authentic or that the pool was not manually filtered before submissionDraw proof filesProofs are saved by date automatically; open the folder to upload .srproof.json files to the verification websiteOpen proof folderOpen verification websiteLocal proof storage limitAfter each new proof, the oldest proof files are deleted when this limit is exceeded; 64 MB by default16 MB32 MB64 MB128 MB256 MB512 MB1 GBLocal proof retentionOnly local .srproof.json files are cleaned; shared website links are not affected; expired files are removed when the next proof is generated7 days15 days30 days60 days90 daysNever clearDraw VerificationServer replay verification succeeded; the proof was savedThe server is temporarily unavailable. A locally replayable proof was saved; you can upload it to the verification website laterProof submission queueOrdinary-mode proofs are saved immediately and submitted for server replay verification in the background, failures are retried automatically, and submission resumes after reconnecting or restartingRetry nowAll proofs have been submitted for server verification{0} awaiting submission{0} failed{0} proof files changed during submission{0} awaiting time stamp diff --git a/SecRandom/Langs/SettingsPages/General/Verification/Resources.ja-JP.resx b/SecRandom/Langs/SettingsPages/General/Verification/Resources.ja-JP.resx index 2d99cac9f..3e4cbd99c 100644 --- a/SecRandom/Langs/SettingsPages/General/Verification/Resources.ja-JP.resx +++ b/SecRandom/Langs/SettingsPages/General/Verification/Resources.ja-JP.resx @@ -1,6 +1,4 @@ -抽選検証検証可能な抽選サーバー検証通常モードはローカルですぐに抽選し、オフラインでも利用して再現可能な証明を保存できます。オンライン時は新しい証明をバックグラウンドでサーバーへ送って再現検証し、第三者タイムスタンプも取得します(送るのは証明のダイジェストのみで、名簿や抽選内容は送りません)。オフラインで保存した履歴証明は自動送信されません。証明は追記型ハッシュチェーンとして保存されるため、事後の改変・証明の削除・チェーンの作り直しを検出できます。また証明は使用した名簿のレコード ID と表示情報の対応ダイジェストを約束するため、抽選後に名簿を書き換えても検出できます。ただし抽選前のローカルアプリ、乱数種、名簿の変更や、抽選前の名簿の絞り込みは証明しません検証可能な抽選モード通常モードはオフラインでローカル抽選し、後で手動検証でき、正式公証モードではサーバーが候補プールを固定し、乱数材料を生成して結果を計算します通常モード正式公証モード検証可能な抽選モードを切り替え内容を読み、切り替えますキャンセル上記の制限を読み、理解しました通常モードはローカルですぐに抽選し、オフラインでも再現可能な証明を保存します。オンライン時、アプリは新しく完了した通常抽選ごとに fair.sectl.cn へ再現署名要求を1回だけバックグラウンド送信し、第三者タイムスタンプも取得します(送るのは証明のダイジェストのみで、名簿や抽選内容は送りません)。オフラインや失敗した履歴証明は自動送信されません。 - -証明は追記型ハッシュチェーンとして保存されるため、事後の改変・証明の削除・チェーンの作り直しを検出できます。サーバーは端末ごとに確認したチェーン先頭も記憶するため、ローカル証明を全て消して作り直すとチェーン位置の後退として報告されます。 +抽選検証検証可能な抽選サーバー検証通常モードはローカルですぐに抽選し、オフラインでも利用して再現可能な証明を保存できます。オンライン時は新しい証明をバックグラウンドでサーバーへ送って再現検証し、第三者タイムスタンプも取得します(送るのは証明のダイジェストのみで、名簿や抽選内容は送りません)。オフラインで保存した履歴証明は自動送信されません。証明は使用した名簿のレコード ID と表示情報の対応ダイジェストを約束するため、抽選後に名簿を書き換えても検出できます。ただし抽選前のローカルアプリ、乱数種、名簿の変更や、抽選前の名簿の絞り込みは証明しません検証可能な抽選モード通常モードはオフラインでローカル抽選し、後で手動検証でき、正式公証モードではサーバーが候補プールを固定し、乱数材料を生成して結果を計算します通常モード正式公証モード検証可能な抽選モードを切り替え内容を読み、切り替えますキャンセル上記の制限を読み、理解しました通常モードはローカルですぐに抽選し、オフラインでも再現可能な証明を保存します。オンライン時、アプリは新しく完了した通常抽選ごとに fair.sectl.cn へ再現署名要求を1回だけバックグラウンド送信し、第三者タイムスタンプも取得します(送るのは証明のダイジェストのみで、名簿や抽選内容は送りません)。オフラインや失敗した履歴証明は自動送信されません。 証明は使用した名簿の「レコード ID → 氏名・学籍番号・グループ」の対応ダイジェストを約束するため、抽選後に名簿を書き換えて当選レコードを別人に向ける行為も検出できます。 @@ -8,4 +6,4 @@ 通信障害、サービス停止、端末故障などでサーバーの完了証明を取得できない場合、ローカルの代替結果は作らず、通常モードにも自動切り替えしません。固定後の候補プール、重み、ルール、乱数材料、結果は同じ処理中に置換・追加抽選・再計算できません。 -固定後のローカル抽選コード、乱数種、結果ファイルの置換を防ぎますが、実際の名簿の完全性や真正性、送信前の候補選別までは証明できません抽選証明ファイル証明は日付ごとに自動保存され、フォルダーを開くと .srproof.json を検証サイトへアップロードできます証明フォルダーを開く検証サイトを開くローカル証明の容量上限新しい証明を生成した後、上限を超えると古い証明を自動削除し、既定は 64 MB16 MB32 MB64 MB128 MB256 MB512 MB1 GBローカル証明の保存期間端末内の .srproof.json だけを整理し、共有リンクには影響せず、次の証明生成時に期限切れファイルを削除します7日15日30日60日90日削除しない抽選検証サーバーによる再現検証に成功し、証明を保存しましたサーバーを一時利用できません。ローカルで再現可能な証明を保存しました。後で検証サイトへアップロードできます証明の送信キュー通常モードの証明はすぐに保存され、バックグラウンドでサーバーの再現検証へ送信され、失敗時は自動で再試行し、再接続や再起動後も送信を続けます今すぐ再試行すべての証明をサーバー検証へ送信済みです送信待ち {0} 件送信失敗 {0} 件送信中に変更された証明ファイル {0} 件証明チェーンの整合性端末内の証明ハッシュチェーンが連続していて改変されていないかを検証します。ローカルのチェーンは削除や改変を可視化するだけで、それ以前の記録が削除されていないことは証明できません今すぐ検証未検証証明チェーンは完全です全 {0} 件、チェーン済み {1} 件、旧形式 {2} 件欠落 {0}、リンク不整合 {1}、改変 {2}、チェーン先頭超過 {3}、未保存 {4}、期限切れ {5}ローカルのチェーンは削除や改変を可視化するだけで、それ以前の記録が削除されていないことは証明できません解析不可改変あり未対応バージョンリンク不整合ファイル欠落チェーン先頭超過未保存タイムスタンプ未完了 {0} 件サーバーが検出した証明チェーンの異常 {0} 件 +固定後のローカル抽選コード、乱数種、結果ファイルの置換を防ぎますが、実際の名簿の完全性や真正性、送信前の候補選別までは証明できません抽選証明ファイル証明は日付ごとに自動保存され、フォルダーを開くと .srproof.json を検証サイトへアップロードできます証明フォルダーを開く検証サイトを開くローカル証明の容量上限新しい証明を生成した後、上限を超えると古い証明を自動削除し、既定は 64 MB16 MB32 MB64 MB128 MB256 MB512 MB1 GBローカル証明の保存期間端末内の .srproof.json だけを整理し、共有リンクには影響せず、次の証明生成時に期限切れファイルを削除します7日15日30日60日90日削除しない抽選検証サーバーによる再現検証に成功し、証明を保存しましたサーバーを一時利用できません。ローカルで再現可能な証明を保存しました。後で検証サイトへアップロードできます証明の送信キュー通常モードの証明はすぐに保存され、バックグラウンドでサーバーの再現検証へ送信され、失敗時は自動で再試行し、再接続や再起動後も送信を続けます今すぐ再試行すべての証明をサーバー検証へ送信済みです送信待ち {0} 件送信失敗 {0} 件送信中に変更された証明ファイル {0} 件タイムスタンプ未完了 {0} 件 diff --git a/SecRandom/Langs/SettingsPages/General/Verification/Resources.resx b/SecRandom/Langs/SettingsPages/General/Verification/Resources.resx index de6fba6b0..70d3cdd61 100644 --- a/SecRandom/Langs/SettingsPages/General/Verification/Resources.resx +++ b/SecRandom/Langs/SettingsPages/General/Verification/Resources.resx @@ -7,7 +7,7 @@ 抽取验证 可验证抽取 服务端验证 - 普通模式在本地立即抽取,断网时仍可使用并保存本地可重放证明;联网后会为新证明后台提交服务端重放验证,并申请第三方时间戳(只发送证明摘要,不发送名单或抽取内容);历史证明不会自动补传,可联网后手动上传到验证网站;证明按追加式哈希链保存,事后改动、删除旧证明、删光重建都能被发现;证明还会承诺抽取时所用名单的记录映射摘要,抽取之后再改名单同样会被发现;但它不证明抽取之前的本地程序、随机种子或名单未被改动,也不能排除抽取前先筛选名单再抽取 + 普通模式在本地立即抽取,断网时仍可使用并保存本地可重放证明;联网后会为新证明后台提交服务端重放验证,并申请第三方时间戳(只发送证明摘要,不发送名单或抽取内容);历史证明不会自动补传,可联网后手动上传到验证网站;证明还会承诺抽取时所用名单的记录映射摘要,抽取之后再改名单同样会被发现;但它不证明抽取之前的本地程序、随机种子或名单未被改动,也不能排除抽取前先筛选名单再抽取 可验证抽取模式 普通模式可离线在本地立即抽取并在联网后手动验证;正式公证模式由服务端锁定候选池、生成随机材料并计算最终结果 普通模式 @@ -18,8 +18,6 @@ 我已阅读并理解上述限制 普通模式会立即在本地抽取,断网时仍可完成抽取并保存本地可重放证明;联网时,应用只为新完成的普通抽取在后台向 fair.sectl.cn 提交一次重放签名请求,并向第三方时间戳服务申请时间戳(只发送证明摘要,不发送名单或抽取内容);离线保存或失败的历史证明不会自动补传,可在联网后手动上传到验证网站 -证明按追加式哈希链保存,因此事后修改、删除旧证明、删光重建都能被发现;服务端还会记住每台设备见过的链头,把本地证明删光重建会被识别为链位置回退 - 证明会承诺抽取时所用名单的「记录 ID → 姓名/学号/组别」映射摘要,所以抽取之后再改名单、把中签记录指向别人同样会被发现 它不能证明抽取之前的本地程序、真实名单或随机种子未被修改,也不能排除抽取前反复试验后再选结果,或在抽取前先筛选名单 @@ -61,21 +59,21 @@ 检测到 {0} 项证明内容在提交期间被改动 - 证明链完整性 - 校验本机证明文件的哈希链是否连续、内容是否被改动;本地链只能让删改可见,不能证明没有更早的记录被删除 - 开始验证 - 尚未验证 - 证明链完整 - 共 {0} 份,已入链 {1} 份,旧格式 {2} 份 - 缺口 {0},断链 {1},被改动 {2},超出链头 {3},未落盘 {4},已过期 {5} - 本地链只能发现删改,不能证明没有更早的记录被删除 - 无法解析 - 内容被改动 - 版本不支持 - 链不衔接 - 缺少文件 - 超出链头 - 未落盘 + + + + + + + + + + + + + + + 时间戳未完成 {0} 项 - 服务端发现 {0} 项证明链异常 + diff --git a/SecRandom/Langs/SettingsPages/Security/Resources.Security.cs b/SecRandom/Langs/SettingsPages/Security/Resources.Security.cs index b3a04dbff..3213cfb22 100644 --- a/SecRandom/Langs/SettingsPages/Security/Resources.Security.cs +++ b/SecRandom/Langs/SettingsPages/Security/Resources.Security.cs @@ -17,18 +17,6 @@ public partial class Resources public static string S_Factors_D => Text(nameof(S_Factors_D)); public static string S_RequireAll => Text(nameof(S_RequireAll)); public static string S_RequireAll_D => Text(nameof(S_RequireAll_D)); - public static string S_SettingsIntegrity => Text(nameof(S_SettingsIntegrity)); - public static string S_SettingsIntegrity_D => Text(nameof(S_SettingsIntegrity_D)); - public static string S_IntegritySection => Text(nameof(S_IntegritySection)); - public static string S_IntegrityAction => Text(nameof(S_IntegrityAction)); - public static string S_IntegrityAction_D => Text(nameof(S_IntegrityAction_D)); - public static string S_IntegrityRestoreSource => Text(nameof(S_IntegrityRestoreSource)); - public static string S_IntegrityRestoreSource_D => Text(nameof(S_IntegrityRestoreSource_D)); - public static string O_IntegrityAction_Confirm => Text(nameof(O_IntegrityAction_Confirm)); - public static string O_IntegrityAction_AutoRestore => Text(nameof(O_IntegrityAction_AutoRestore)); - public static string O_IntegrityRestoreSource_Local => Text(nameof(O_IntegrityRestoreSource_Local)); - public static string O_IntegrityRestoreSource_LocalThenCloud => Text(nameof(O_IntegrityRestoreSource_LocalThenCloud)); - public static string O_IntegrityRestoreSource_CloudThenLocal => Text(nameof(O_IntegrityRestoreSource_CloudThenLocal)); public static string S_WindowOperations => Text(nameof(S_WindowOperations)); public static string S_WindowOperations_D => Text(nameof(S_WindowOperations_D)); public static string S_DrawOperations => Text(nameof(S_DrawOperations)); @@ -80,9 +68,6 @@ public partial class Resources public static string C_SelectUsb => Text(nameof(C_SelectUsb)); public static string C_SelectedUsb => Text(nameof(C_SelectedUsb)); public static string C_Copy => Text(nameof(C_Copy)); - public static string C_IntegrityAccept => Text(nameof(C_IntegrityAccept)); - public static string C_IntegrityExit => Text(nameof(C_IntegrityExit)); - public static string C_IntegrityRecoverContinue => Text(nameof(C_IntegrityRecoverContinue)); public static string M_PasswordDialogTitle => Text(nameof(M_PasswordDialogTitle)); public static string M_SetPasswordDialogTitle => Text(nameof(M_SetPasswordDialogTitle)); public static string M_TotpDialogTitle => Text(nameof(M_TotpDialogTitle)); @@ -104,20 +89,6 @@ public partial class Resources public static string M_VerificationTotpStandalonePending => Text(nameof(M_VerificationTotpStandalonePending)); public static string M_VerificationUnavailable => Text(nameof(M_VerificationUnavailable)); public static string M_LockoutFormat => Text(nameof(M_LockoutFormat)); - public static string M_IntegrityDialogTitle => Text(nameof(M_IntegrityDialogTitle)); - public static string M_IntegrityDetectedHeader => Text(nameof(M_IntegrityDetectedHeader)); - public static string M_IntegrityDetectedFormat => Text(nameof(M_IntegrityDetectedFormat)); - public static string M_IntegrityUnknownValue => Text(nameof(M_IntegrityUnknownValue)); - public static string M_IntegrityRecoverTitle => Text(nameof(M_IntegrityRecoverTitle)); - public static string M_IntegrityRecovering => Text(nameof(M_IntegrityRecovering)); - public static string M_IntegrityRecoverSuccessFormat => Text(nameof(M_IntegrityRecoverSuccessFormat)); - public static string M_IntegrityRecoverFailedFormat => Text(nameof(M_IntegrityRecoverFailedFormat)); - public static string M_IntegrityRecoverFallback => Text(nameof(M_IntegrityRecoverFallback)); - public static string M_IntegritySourceLocal => Text(nameof(M_IntegritySourceLocal)); - public static string M_IntegritySourceCloud => Text(nameof(M_IntegritySourceCloud)); - public static string M_IntegrityNoBackup => Text(nameof(M_IntegrityNoBackup)); - public static string M_IntegrityNotSignedIn => Text(nameof(M_IntegrityNotSignedIn)); - public static string M_IntegrityBackupInvalid => Text(nameof(M_IntegrityBackupInvalid)); public static string M_UsbPresent => Text(nameof(M_UsbPresent)); public static string M_UsbMissing => Text(nameof(M_UsbMissing)); public static string M_PasswordRemoved => Text(nameof(M_PasswordRemoved)); diff --git a/SecRandom/Langs/SettingsPages/Security/Resources.en-US.resx b/SecRandom/Langs/SettingsPages/Security/Resources.en-US.resx index 5163465cc..0e8f2faba 100644 --- a/SecRandom/Langs/SettingsPages/Security/Resources.en-US.resx +++ b/SecRandom/Langs/SettingsPages/Security/Resources.en-US.resx @@ -30,35 +30,6 @@ A password protects the credentials; add other configured methods when needed Require All Selected Methods When on, complete all selected verification methods; when off, any one selected method is sufficient — using TOTP this way stores its secret in a readable form inside the data directory - Tamper Protection - Settings File Tamper Check - Records a fingerprint of the whole settings file and verifies at startup that it was not changed outside the app - Tamper Response - Action to take when the check finds the settings file changed outside the app - Require the security password before continuing - Automatically restore the latest backup - Restore Source - Backup sources tried in order during automatic restore; cloud backups need a signed-in account and only this device's own uploads are used, never another device's backup - Local backups only - Local first, cloud when missing - Cloud first, local when that fails - Settings File Tamper Check - The settings file was modified outside the app - Last recorded: {0} (version {1}) Current file modification time: {2} Confirm with the security password to accept the current settings file, otherwise the app will exit - Unknown - Settings File Auto Recovery - Restoring the settings file from backup, please wait - Restored the settings file from the {0} backup "{1}" The previous settings file was saved as: {2} The app will restart automatically in a few seconds - Automatic recovery failed: {0} - Confirm the current settings file with the security password, otherwise the app will exit - local - cloud - No usable backup containing the settings file was found - No account is signed in, so cloud backups are unavailable - The backup is invalid or does not contain the settings file - Verify and Continue - Exit - Continue Windows and App Protect settings, window visibility, and app lifecycle actions Draws @@ -152,7 +123,7 @@ How long verification is skipped after a successful one seconds Operations: draws, resets, window toggles, exiting the app, shortcuts and IPC commands - Settings window: after opening settings with verification, changes in this window are covered too, while closing the window ends it immediately; changes that loosen protection, such as turning security off, clearing a factor, disabling the settings-integrity check or lengthening this duration, always ask for the security password again + Settings window: after opening settings with verification, changes in this window are covered too, while closing the window ends it immediately; changes that loosen protection, such as turning security off, clearing a factor or lengthening this duration, always ask for the security password again Never affected: setting up or removing TOTP, changing or removing the password and binding a USB device always ask again Exit Sudo Mode Sudo mode deactivated diff --git a/SecRandom/Langs/SettingsPages/Security/Resources.ja-JP.resx b/SecRandom/Langs/SettingsPages/Security/Resources.ja-JP.resx index 4dbe56810..e6d2311eb 100644 --- a/SecRandom/Langs/SettingsPages/Security/Resources.ja-JP.resx +++ b/SecRandom/Langs/SettingsPages/Security/Resources.ja-JP.resx @@ -30,35 +30,6 @@ パスワードは認証情報を保護し、設定済みの方式を追加できます 選択したすべての方式を要求 オンの場合は選択したすべての認証方式が必要で、オフの場合はいずれか一つで続行でき、TOTP を選ぶとシークレットがデータディレクトリに読み取り可能な形式で保存されます - 改ざん対策 - 設定ファイルの改ざんチェック - 有効にすると設定ファイル全体のフィンガープリントを記録し、起動時にアプリ以外から変更されていないかを確認します - 改ざん時の動作 - 設定ファイルがアプリ以外から変更されているのを検出したときに実行する操作 - 安全パスワードで確認してから続行する - 最新のバックアップから自動的に復元する - 復元データの取得元 - 自動復元時に順番に試すバックアップの取得元で、クラウドバックアップにはログインが必要であり、このデバイスがアップロードしたものだけを使用し、他のデバイスのバックアップは使用しません - ローカルバックアップのみ - ローカル優先、なければクラウド - クラウド優先、失敗時はローカル - 設定ファイルの改ざんチェック - 設定ファイルが外部から変更されました - 最後の記録: {0}(バージョン {1}) 現在のファイル更新時刻: {2} パスワードで確認すると現在の設定ファイルを採用します。確認できない場合はアプリを終了します - 不明 - 設定ファイルの自動復元 - バックアップから設定ファイルを復元しています。しばらくお待ちください - {0}バックアップ「{1}」から設定ファイルを復元しました 復元前の設定ファイルは次に保存しました: {2} 数秒後にアプリが自動的に再起動します - 自動復元に失敗しました: {0} - 安全パスワードで現在の設定ファイルを確認してください。確認しない場合はアプリが終了します - ローカル - クラウド - 設定ファイルを含む利用可能なバックアップが見つかりません - アカウントにログインしていないため、クラウドバックアップを利用できません - バックアップが無効か、設定ファイルが含まれていません - 認証して続行 - 終了 - 続行 ウィンドウとアプリ 設定、ウィンドウ表示、アプリ操作を保護します 抽選 @@ -152,7 +123,7 @@ 認証成功後に再認証を省略する時間 秒 操作:抽選、リセット、ウィンドウの表示切り替え、アプリの終了、ショートカット、IPC コマンド - 設定ウィンドウ:設定を開く際の認証後はこのウィンドウ内の変更も省略できますが、閉じると即座に無効になります。保護を緩める変更(セキュリティ保護の停止、認証方式の解除、改ざんチェックの停止、この時間の延長など)は常にパスワードの再入力が必要です + 設定ウィンドウ:設定を開く際の認証後はこのウィンドウ内の変更も省略できますが、閉じると即座に無効になります。保護を緩める変更(セキュリティ保護の停止、認証方式の解除、この時間の延長など)は常にパスワードの再入力が必要です 影響を受けない操作:TOTP の設定・削除、パスワードの変更・削除、USB デバイスの登録は常に再認証が必要です Sudo モードを終了 Sudo モードを無効にしました diff --git a/SecRandom/Langs/SettingsPages/Security/Resources.resx b/SecRandom/Langs/SettingsPages/Security/Resources.resx index 93b461d14..e2ab7d85a 100644 --- a/SecRandom/Langs/SettingsPages/Security/Resources.resx +++ b/SecRandom/Langs/SettingsPages/Security/Resources.resx @@ -59,35 +59,6 @@ 密码用于保护凭据;可额外选择已经配置的验证方式 全部已选验证方式均需验证 开启时必须完成全部已选验证方式;关闭时任选一种已选方式通过即可继续,此时 TOTP 密钥会以可读形式保存在数据目录中 - 防篡改 - 设置文件防篡改校验 - 开启后记录整份设置文件的指纹,启动时校验该文件是否被程序之外修改 - 篡改处理方式 - 校验发现设置文件被程序之外修改后要执行的操作 - 需要安全密码确认后继续 - 自动恢复最近一次备份 - 恢复数据来源 - 自动恢复时依次尝试的备份来源,云端备份需要已登录账号且只使用本机上传的备份,不会使用其他设备的备份 - 仅本地备份 - 本地优先,缺失时使用云端备份 - 云端优先,失败时使用本地备份 - 设置文件防篡改校验 - 设置文件已被外部修改 - 最后一次记录:{0}(版本 {1}) 当前文件修改时间:{2} 请使用安全密码确认以接受当前设置文件,否则程序将退出 - 未知 - 设置文件自动恢复 - 正在从备份恢复设置文件,请稍候 - 已从{0}备份「{1}」恢复设置文件 恢复前的设置文件已另存为:{2} 应用将在几秒后自动重启 - 自动恢复失败:{0} - 请使用安全密码确认当前设置文件,否则程序将退出 - 本地 - 云端 - 未找到包含设置文件的可用备份 - 未登录账号,云端备份不可用 - 备份无效或不包含设置文件 - 验证并继续 - 退出程序 - 继续 窗口与应用 保护设置入口、窗口显隐及应用生命周期操作 抽取 @@ -181,7 +152,7 @@ 验证通过后的免验证时长 秒 操作范围:抽取、重置、开关窗口、退出程序、快捷键与 IPC 指令 - 设置窗口范围:打开设置验证后,本窗口内的设置改动同样免验证,但关闭窗口会立即失效;关闭安全保护、取消验证方式、关闭防篡改校验或延长本时长等放宽防护的改动,始终需要重新输入安全密码 + 设置窗口范围:打开设置验证后,本窗口内的设置改动同样免验证,但关闭窗口会立即失效;关闭安全保护、取消验证方式或延长本时长等放宽防护的改动,始终需要重新输入安全密码 不受影响的操作:配置或移除 TOTP、修改或移除密码、绑定 USB 设备始终需要重新验证 退出 Sudo 模式 已退出 Sudo 模式 diff --git a/SecRandom/Models/CloudBackupMetadata.cs b/SecRandom/Models/CloudBackupMetadata.cs deleted file mode 100644 index 96f075bb9..000000000 --- a/SecRandom/Models/CloudBackupMetadata.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System; - -namespace SecRandom.Models; - -public class CloudBackupMetadata -{ - public string BackupId { get; set; } = string.Empty; - public string DisplayName { get; set; } = string.Empty; - public DateTime DateTime { get; set; } = DateTime.MinValue; - public string Size { get; set; } = string.Empty; - public bool IsComplete { get; set; } = true; - public int PartCount { get; set; } - public string StatusText { get; set; } = string.Empty; - - /// - /// Whether the package was uploaded by the removed client-side encryption feature, taken from - /// the cloud file names so the listing can flag it without a manifest download per backup. - /// - public bool IsLegacyEncrypted { get; set; } -} diff --git a/SecRandom/Services/Auth/SectlCloudStorageClient.cs b/SecRandom/Services/Auth/SectlCloudStorageClient.cs deleted file mode 100644 index 4c929f693..000000000 --- a/SecRandom/Services/Auth/SectlCloudStorageClient.cs +++ /dev/null @@ -1,325 +0,0 @@ -using System.Diagnostics; -using System.Net; -using System.Net.Http.Json; -using System.Text.Json; -using System.Text.Json.Serialization; -using Microsoft.Extensions.Logging; - -namespace SecRandom.Services.Auth; - -public sealed record SectlCloudFile(string FileId, string? FileDocumentId, string FileName, long Size, DateTimeOffset? CreatedAt); - -public sealed record SectlCloudQuota(long Used, long Total, long Available, int FileCount, long PlatformUsed, int PlatformFileCount); - -/// -/// Cloud API failure with the service error code kept intact so the UI can localize -/// "signed out", "cloud disabled", "quota exceeded", and transport failures differently. -/// -public sealed class SectlCloudStorageException(string code, string description) : Exception(description) -{ - public string Code { get; } = code; -} - -/// -/// Typed client for the SECTL personal cloud storage API (/api/cloud/*, Appwrite cloud -/// function). Requests carry the signed-in OAuth bearer token plus the SecRandom platform -/// client_id, so the account, the platform scope, and the quota are all resolved -/// server-side. Only the account cloud sync path uses this client; the anonymous device-transfer -/// channel stays on SecRandom Sync. -/// -public sealed class SectlCloudStorageClient( - SectlAuthService authService, - IHttpClientFactory httpClientFactory, - ILogger logger) -{ - private const string CloudPath = "api/cloud"; - private const string HttpClientName = "sectl-cloud"; - private const int PageSize = 500; - - /// One upload part never exceeds this size; release parts stay far below it. - private const long MaxUploadBytes = 4L * 1024 * 1024; - - private const long MaxDownloadBytes = 8L * 1024 * 1024; - - /// - /// Server responses slower than this are treated as an execution timeout: the SECTL cloud - /// function spends that long scanning per-user storage usage before it answers, and the - /// gateway answers the client with a bare 5xx while the execution keeps running. - /// - private static readonly TimeSpan SlowServerThreshold = TimeSpan.FromSeconds(10); - - private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web); - - public async Task> ListFilesAsync(CancellationToken cancellationToken = default) - { - var files = new List(); - for (var offset = 0; ; offset += PageSize) - { - var body = await SendForBodyAsync( - () => new HttpRequestMessage(HttpMethod.Get, BuildUri("files", $"limit={PageSize}&offset={offset}")), - cancellationToken).ConfigureAwait(false); - CloudFileListResponse? payload; - try - { - payload = JsonSerializer.Deserialize(body, JsonOptions); - } - catch (JsonException exception) - { - throw new SectlCloudStorageException("invalid_response", $"云端文件列表无法解析:{exception.Message}"); - } - - if (payload?.Files is null) - return files; - - foreach (var file in payload.Files) - { - if (string.IsNullOrWhiteSpace(file.FileId) || string.IsNullOrWhiteSpace(file.FileName)) - continue; - files.Add(new SectlCloudFile(file.FileId!, file.FileDocumentId, file.FileName!, - file.Size ?? 0, ParseTimestamp(file.CreatedAt))); - } - - if (!payload.HasMore || payload.Files.Count == 0) - return files; - } - } - - public async Task UploadAsync(string fileName, string mimeType, byte[] content, - CancellationToken cancellationToken = default) - { - ArgumentException.ThrowIfNullOrWhiteSpace(fileName); - ArgumentNullException.ThrowIfNull(content); - if (content.LongLength > MaxUploadBytes) - throw new SectlCloudStorageException("payload_too_large", "云端备份分片体积超过上传限制。"); - - var payload = new - { - client_id = SectlAuthService.ClientId, - file = new - { - name = fileName, - type = mimeType, - size = content.LongLength, - data = $"data:{mimeType};base64,{Convert.ToBase64String(content)}" - } - }; - var body = await SendForBodyAsync( - () => new HttpRequestMessage(HttpMethod.Post, BuildUri("upload")) - { - Content = JsonContent.Create(payload, options: JsonOptions) - }, - cancellationToken).ConfigureAwait(false); - CloudUploadResponse? uploaded; - try - { - uploaded = JsonSerializer.Deserialize(body, JsonOptions); - } - catch (JsonException exception) - { - throw new SectlCloudStorageException("upload_failed", $"云端上传结果无法解析:{exception.Message}"); - } - - if (uploaded?.Success != true || string.IsNullOrWhiteSpace(uploaded.FileId)) - throw new SectlCloudStorageException("upload_failed", "云端未确认分片上传结果。"); - - return new SectlCloudFile(uploaded.FileId!, null, uploaded.FileName ?? fileName, - uploaded.Size ?? content.LongLength, DateTimeOffset.UtcNow); - } - - public async Task DownloadAsync(string fileId, CancellationToken cancellationToken = default) - { - ArgumentException.ThrowIfNullOrWhiteSpace(fileId); - var body = await SendForBodyAsync( - () => new HttpRequestMessage(HttpMethod.Get, BuildUri($"files/{Uri.EscapeDataString(fileId)}/download")), - cancellationToken).ConfigureAwait(false); - CloudDownloadResponse? access; - try - { - access = JsonSerializer.Deserialize(body, JsonOptions); - } - catch (JsonException exception) - { - throw new SectlCloudStorageException("download_failed", $"云端下载地址无法解析:{exception.Message}"); - } - - if (string.IsNullOrWhiteSpace(access?.DownloadUrl)) - throw new SectlCloudStorageException("download_failed", "云端未返回下载地址。"); - - using var request = new HttpRequestMessage(HttpMethod.Get, access.DownloadUrl); - // A factory-provided client is shared; dispose only the response, never the client. - var client = httpClientFactory.CreateClient(HttpClientName); - using HttpResponseMessage download = await client - .SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); - if (!download.IsSuccessStatusCode) - throw CreateException(download.StatusCode, string.Empty); - - await using var stream = await download.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); - using var output = new MemoryStream(); - var buffer = new byte[81920]; - int read; - while ((read = await stream.ReadAsync(buffer, cancellationToken).ConfigureAwait(false)) > 0) - { - if (output.Length + read > MaxDownloadBytes) - throw new SectlCloudStorageException("payload_too_large", "云端备份分片体积超过下载限制。"); - output.Write(buffer, 0, read); - } - - return output.ToArray(); - } - - public async Task DeleteAsync(string fileId, string? fileDocumentId, CancellationToken cancellationToken = default) - { - ArgumentException.ThrowIfNullOrWhiteSpace(fileId); - var payload = new Dictionary { ["client_id"] = SectlAuthService.ClientId }; - if (!string.IsNullOrWhiteSpace(fileDocumentId)) - payload["file_document_id"] = fileDocumentId; - - await SendForBodyAsync( - () => new HttpRequestMessage(HttpMethod.Delete, BuildUri($"files/{Uri.EscapeDataString(fileId)}")) - { - Content = JsonContent.Create(payload, options: JsonOptions) - }, - cancellationToken).ConfigureAwait(false); - } - - public async Task GetUsageAsync(CancellationToken cancellationToken = default) - { - var body = await SendForBodyAsync( - () => new HttpRequestMessage(HttpMethod.Get, BuildUri("storage/usage")), - cancellationToken).ConfigureAwait(false); - CloudUsageResponse? payload; - try - { - payload = JsonSerializer.Deserialize(body, JsonOptions); - } - catch (JsonException exception) - { - throw new SectlCloudStorageException("invalid_response", $"云端用量无法解析:{exception.Message}"); - } - - if (payload is null) - throw new SectlCloudStorageException("invalid_response", "云端未返回用量信息。"); - return new SectlCloudQuota(payload.UsedStorage, payload.TotalStorage, payload.AvailableStorage, - payload.FileCount, payload.PlatformUsedStorage, payload.PlatformFileCount); - } - - private static string BuildUri(string path, string? extraQuery = null) - { - var uri = $"{SectlAuthService.ApiBaseUrl}/{CloudPath}/{path}?client_id={Uri.EscapeDataString(SectlAuthService.ClientId)}"; - return string.IsNullOrWhiteSpace(extraQuery) ? uri : $"{uri}&{extraQuery}"; - } - - private static DateTimeOffset? ParseTimestamp(string? value) => - DateTimeOffset.TryParse(value, out var timestamp) ? timestamp : null; - - /// - /// Sends one cloud API request and returns its success body, keeping the elapsed time so a - /// failing gateway response can be classified as a server-side execution timeout. - /// - private async Task SendForBodyAsync(Func createRequest, - CancellationToken cancellationToken) - { - var stopwatch = Stopwatch.StartNew(); - using HttpResponseMessage response = await authService.SendAuthorizedAsync(createRequest, - HttpCompletionOption.ResponseContentRead, cancellationToken).ConfigureAwait(false); - var body = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); - stopwatch.Stop(); - if (response.IsSuccessStatusCode) - return body; - - var exception = CreateException(response.StatusCode, body, stopwatch.Elapsed); - logger.LogWarning( - "云端接口请求失败:状态={Status},耗时={ElapsedMs}ms,错误码={Code},响应={Body}", - (int)response.StatusCode, stopwatch.ElapsedMilliseconds, exception.Code, Truncate(body, 300)); - throw exception; - } - - private static string Truncate(string value, int maximumLength) => - value.Length <= maximumLength ? value : value[..maximumLength] + "…"; - - private static SectlCloudStorageException CreateException(HttpStatusCode statusCode, string body, - TimeSpan? elapsed = null) - { - string? functionCode = null; - string? description = null; - string? appwriteCode = null; - if (!string.IsNullOrWhiteSpace(body)) - { - try - { - using var document = JsonDocument.Parse(body); - if (document.RootElement.ValueKind == JsonValueKind.Object) - { - if (document.RootElement.TryGetProperty("error", out var error) && error.ValueKind == JsonValueKind.String) - functionCode = error.GetString(); - if (document.RootElement.TryGetProperty("error_description", out var detail) && detail.ValueKind == JsonValueKind.String) - description = detail.GetString(); - if (document.RootElement.TryGetProperty("type", out var type) && type.ValueKind == JsonValueKind.String) - appwriteCode = type.GetString(); - if (description is null - && document.RootElement.TryGetProperty("message", out var message) - && message.ValueKind == JsonValueKind.String) - description = message.GetString(); - } - } - catch (JsonException) - { - // A non-JSON error body still maps through the status code below. - } - } - - var isServerError = (int)statusCode >= 500; - var slow = elapsed is { } duration && duration >= SlowServerThreshold; - if (isServerError && functionCode is null) - { - // The SECTL cloud function answers its own failures with an `error` envelope. A bare or - // non-function 5xx is the gateway giving up while the execution keeps running, which is - // the shape a slow per-user storage usage scan produces today. - var reason = string.IsNullOrWhiteSpace(description) - ? "服务端未返回错误详情(空响应)" - : description!; - return new SectlCloudStorageException("cloud_timeout", - $"云端服务响应超时或不可用(HTTP {(int)statusCode},耗时 {(elapsed?.TotalSeconds ?? 0):0.#}s):{reason}"); - } - - if (isServerError && slow) - { - return new SectlCloudStorageException("cloud_timeout", - $"云端服务响应超时(HTTP {(int)statusCode},耗时 {elapsed!.Value.TotalSeconds:0.#}s):{description ?? functionCode}"); - } - - var code = functionCode ?? appwriteCode ?? - (statusCode == HttpStatusCode.RequestEntityTooLarge ? "payload_too_large" : $"http_{(int)statusCode}"); - return new SectlCloudStorageException(code, - string.IsNullOrWhiteSpace(description) ? $"云端请求失败({(int)statusCode})。" : description!); - } - - private sealed record CloudFileListResponse( - [property: JsonPropertyName("files")] List? Files, - [property: JsonPropertyName("has_more")] bool HasMore); - - private sealed record CloudFilePayload( - [property: JsonPropertyName("file_id")] string? FileId, - [property: JsonPropertyName("file_document_id")] string? FileDocumentId, - [property: JsonPropertyName("filename")] string? FileName, - [property: JsonPropertyName("size")] long? Size, - [property: JsonPropertyName("created_at")] string? CreatedAt); - - private sealed record CloudUploadResponse( - [property: JsonPropertyName("success")] bool? Success, - [property: JsonPropertyName("file_id")] string? FileId, - [property: JsonPropertyName("filename")] string? FileName, - [property: JsonPropertyName("size")] long? Size); - - private sealed record CloudDownloadResponse( - [property: JsonPropertyName("download_url")] string? DownloadUrl, - [property: JsonPropertyName("expires_at")] string? ExpiresAt); - - private sealed record CloudUsageResponse( - [property: JsonPropertyName("used_storage")] long UsedStorage, - [property: JsonPropertyName("total_storage")] long TotalStorage, - [property: JsonPropertyName("available_storage")] long AvailableStorage, - [property: JsonPropertyName("file_count")] int FileCount, - [property: JsonPropertyName("platform_used_storage")] long PlatformUsedStorage, - [property: JsonPropertyName("platform_file_count")] int PlatformFileCount); -} diff --git a/SecRandom/Services/ImportExport/CloudAutomaticBackupService.cs b/SecRandom/Services/ImportExport/CloudAutomaticBackupService.cs deleted file mode 100644 index f10cfc218..000000000 --- a/SecRandom/Services/ImportExport/CloudAutomaticBackupService.cs +++ /dev/null @@ -1,79 +0,0 @@ -using System; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.Extensions.Hosting; -using Microsoft.Extensions.Logging; -using SecRandom.Core.Services.Config; - -namespace SecRandom.Services.ImportExport; - -/// -/// Desktop-only automatic cloud backup. It runs on the configured cadence while the app is open -/// and a SECTL account is signed in, and delegates every storage decision to -/// , which keeps the account inside its quota and keeps each -/// signed-in device inside its own retention budget. -/// -public sealed class CloudAutomaticBackupService( - MainConfigHandler configHandler, - CloudBackupService cloudBackupService, - ILogger logger) : BackgroundService -{ - private static readonly TimeSpan CheckInterval = TimeSpan.FromHours(1); - - protected override async Task ExecuteAsync(CancellationToken stoppingToken) - { - await Task.Yield(); - - while (!stoppingToken.IsCancellationRequested) - { - try - { - await CreateBackupWhenDueAsync(stoppingToken).ConfigureAwait(false); - } - catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) - { - break; - } - catch (Exception ex) - { - logger.LogError(ex, "云端自动备份失败。"); - } - - try - { - await Task.Delay(CheckInterval, stoppingToken).ConfigureAwait(false); - } - catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) - { - break; - } - } - } - - private async Task CreateBackupWhenDueAsync(CancellationToken cancellationToken) - { - var settings = configHandler.Data.General.Backup; - if (!settings.CloudAutoBackupEnabled || !cloudBackupService.IsSignedIn) - return; - - var intervalDays = Math.Max(1, settings.CloudAutoBackupIntervalDays); - if (!await IsDueAsync(intervalDays, cancellationToken).ConfigureAwait(false)) - return; - - var descriptor = await cloudBackupService - .UploadAutomaticAsync(settings.CloudAutoBackupMaxCount, cancellationToken: cancellationToken) - .ConfigureAwait(false); - logger.LogInformation("已创建云端自动备份:备份={BackupId}。", descriptor.BackupId); - } - - /// - /// This device's newest cloud backup decides the cadence, so a manual upload also postpones the - /// next automatic one instead of stacking a duplicate right after it, while a second signed-in - /// machine's uploads neither postpone nor trigger this device. - /// - private async Task IsDueAsync(int intervalDays, CancellationToken cancellationToken) - { - var newest = await cloudBackupService.GetLatestOwnBackupTimeAsync(cancellationToken).ConfigureAwait(false); - return newest is null || DateTimeOffset.UtcNow - newest.Value >= TimeSpan.FromDays(intervalDays); - } -} diff --git a/SecRandom/Services/ImportExport/CloudBackupService.cs b/SecRandom/Services/ImportExport/CloudBackupService.cs deleted file mode 100644 index 69a7cf4c6..000000000 --- a/SecRandom/Services/ImportExport/CloudBackupService.cs +++ /dev/null @@ -1,456 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.Extensions.Logging; -using SecRandom.Core; -using SecRandom.Core.Services.Archive; -using SecRandom.Core.Services.Config; -using SecRandom.Mobile; -using SecRandom.Platforms.Abstractions; -using SecRandom.Services.Auth; -using SecRandom.Shared; - -namespace SecRandom.Services.ImportExport; - -/// -/// One cloud backup as the listing sees it. marks a package -/// uploaded by the removed client-side encryption feature: this build cannot derive its key, so it -/// stays listed but is never offered for restore. -/// -public sealed record CloudBackupDescriptor( - string BackupId, - string DisplayName, - DateTimeOffset? CreatedAt, - long TotalBytes, - int PartCount, - bool IsComplete, - string? ManifestFileId, - string DeviceTag = "", - bool IsEncrypted = false) -{ - public bool CanRestore => IsComplete && !string.IsNullOrWhiteSpace(ManifestFileId) && !IsEncrypted; -} - -public sealed record CloudBackupProgress(string Stage, int Completed, int Total) -{ - public const string PartsStage = "parts"; - public const string DoneStage = "done"; -} - -/// -/// Account cloud-sync orchestration for the signed-in SECTL account: packages a cloud backup -/// archive, uploads it as verified parts plus a trailing manifest, lists the backups that belong -/// to this application scope, rebuilds one after per-part and whole-archive verification, and -/// deletes backups. Every upload stamps a device alias into its id, so the list tells several -/// signed-in devices apart and retention stays per device. The anonymous device-transfer channel -/// stays on SecRandom Sync; this service only ever talks to the authenticated SECTL personal -/// cloud API. -/// -/// The account cloud stores the archive as it was produced: client-side encryption was removed -/// on purpose, because a passphrase made the cloud copy useless to anyone who lost it. Account -/// access is now the only key, so any device signed into the same account can list and restore -/// every backup. -/// -/// -public sealed class CloudBackupService( - SectlAuthService authService, - SectlCloudStorageClient cloudClient, - MainConfigHandler configHandler, - IImportExportService importExportService, - ILogger logger, - IPlatformServiceRoot? platform = null) -{ - public bool IsSignedIn => authService.IsSignedIn; - - /// - /// Alias stamped on this device's uploads, empty when the host name yields no ASCII-safe tag. - /// Exposed because a caller that consumes cloud backups has to be able to tell this device's own - /// backups from another signed-in machine's — the alias is a display label, not an identity. - /// - public string DeviceTag => ResolveDeviceTag(); - - /// Whether a listed backup was uploaded by this device. - public bool IsOwnBackup(CloudBackupDescriptor descriptor) => IsOwnBackup(descriptor, DeviceTag); - - internal static bool IsOwnBackup(CloudBackupDescriptor descriptor, string deviceTag) - { - ArgumentNullException.ThrowIfNull(descriptor); - return !string.IsNullOrWhiteSpace(deviceTag) && - string.Equals(descriptor.DeviceTag, deviceTag, StringComparison.OrdinalIgnoreCase); - } - - /// - /// Raised after an automatic upload lands, so an open backup page can reload the list and the - /// (possibly reduced) account quota instead of polling. Manual uploads report through the - /// calling page's own refresh path. - /// - public event EventHandler? AutomaticBackupUploaded; - - public Task GetQuotaAsync(CancellationToken cancellationToken = default) => - cloudClient.GetUsageAsync(cancellationToken); - - public async Task> ListAsync(CancellationToken cancellationToken = default) - { - var files = await cloudClient.ListFilesAsync(cancellationToken).ConfigureAwait(false); - return GroupBackups(files); - } - - /// - /// Packages the current cloud root set and uploads it. Parts are uploaded first and the - /// manifest last, so an interrupted upload can never look like a complete backup; a failure - /// rolls back the parts of this attempt. - /// - public async Task UploadAsync(IProgress? progress = null, - CancellationToken cancellationToken = default) - { - var deviceTag = ResolveDeviceTag(); - var backupId = CloudBackupPackage.CreateBackupId(DateTime.UtcNow, deviceTag); - var archivePath = GetCloudCachePath($"{backupId}.zip"); - var uploaded = new List(); - try - { - // The manifest must describe the roots that were actually packed, so the set is resolved - // from the cloud backup-content selection before the archive is written. - var roots = importExportService.GetCloudBackupRoots(); - await importExportService.ExportCloudBackupAsync(archivePath, cancellationToken).ConfigureAwait(false); - var archive = await File.ReadAllBytesAsync(archivePath, cancellationToken).ConfigureAwait(false); - - // The parts carry exactly what the account cloud stores: the archive itself. Everything the - // manifest hashes and every part name refers to that payload. - var parts = CloudBackupPackage.Slice(archive, CloudBackupPackage.DefaultPartBytes); - var manifest = CloudBackupPackage.BuildManifest(backupId, parts, CloudBackupPackage.DefaultPartBytes, - roots, DateTime.UtcNow, GlobalConstants.Version, archive); - CloudBackupPackage.ValidateManifest(manifest); - - for (var index = 0; index < parts.Count; index++) - { - cancellationToken.ThrowIfCancellationRequested(); - uploaded.Add(await cloudClient - .UploadAsync(manifest.Parts[index].Name, "application/octet-stream", parts[index], cancellationToken) - .ConfigureAwait(false)); - progress?.Report(new CloudBackupProgress(CloudBackupProgress.PartsStage, index + 1, parts.Count + 1)); - } - - var manifestFile = await cloudClient - .UploadAsync(CloudBackupPackage.BuildManifestName(backupId), "application/json", - CloudBackupPackage.SerializeManifest(manifest), cancellationToken) - .ConfigureAwait(false); - uploaded.Add(manifestFile); - progress?.Report(new CloudBackupProgress(CloudBackupProgress.DoneStage, parts.Count + 1, parts.Count + 1)); - logger.LogInformation("云端备份上传完成:备份={BackupId},分片={Parts},大小={Bytes}。", - backupId, parts.Count, archive.LongLength); - return new CloudBackupDescriptor(backupId, manifest.ArchiveName, DateTimeOffset.UtcNow, - archive.LongLength, parts.Count, true, manifestFile.FileId, deviceTag); - } - catch - { - await RollbackAsync(uploaded).ConfigureAwait(false); - throw; - } - finally - { - TryDeleteFile(archivePath); - } - } - - /// - /// Automatic cloud backup. It uploads exactly like the manual path, but it also owns the - /// account's storage budget: an exhausted quota removes the account-wide oldest backup and - /// retries, while the configured retention limit only drops this device's own surplus so - /// another signed-in machine keeps its backups. A manual upload never deletes anything - /// implicitly, so a failure there still surfaces as a quota error. - /// - public async Task UploadAutomaticAsync(int maximumBackups, - IProgress? progress = null, CancellationToken cancellationToken = default) - { - while (true) - { - CloudBackupDescriptor descriptor; - try - { - descriptor = await UploadAsync(progress, cancellationToken).ConfigureAwait(false); - } - catch (SectlCloudStorageException exception) when (exception.Code == "storage_exceeded") - { - var oldest = await FindOldestAsync(cancellationToken).ConfigureAwait(false); - if (oldest is null) - throw; - - logger.LogWarning("云端空间不足,删除最早的云端备份后重试:备份={BackupId}。", oldest.BackupId); - await DeleteAsync(oldest, cancellationToken).ConfigureAwait(false); - continue; - } - - await TrimAsync(maximumBackups, cancellationToken).ConfigureAwait(false); - AutomaticBackupUploaded?.Invoke(this, EventArgs.Empty); - return descriptor; - } - } - - /// - /// Downloads one backup, verifies every part and the rebuilt archive, and returns the local - /// verified archive path. The caller owns the restore step so the existing inspection, - /// confirmation, snapshot, and restart flow stays unchanged. - /// - public async Task DownloadAsync(CloudBackupDescriptor descriptor, - CancellationToken cancellationToken = default) - { - ArgumentNullException.ThrowIfNull(descriptor); - if (!descriptor.CanRestore) - throw new InvalidDataException("云端备份不完整,无法下载恢复。"); - - var manifestBytes = await cloudClient.DownloadAsync(descriptor.ManifestFileId!, cancellationToken) - .ConfigureAwait(false); - var manifest = CloudBackupPackage.DeserializeManifest(manifestBytes); - if (!string.Equals(manifest.BackupId, descriptor.BackupId, StringComparison.Ordinal)) - throw new InvalidDataException("云端备份清单与备份标识不匹配。"); - CloudBackupPackage.ValidateManifest(manifest); - - var files = await cloudClient.ListFilesAsync(cancellationToken).ConfigureAwait(false); - var partsByName = new Dictionary(StringComparer.Ordinal); - foreach (var file in files) - partsByName[file.FileName] = file; - - var parts = new byte[manifest.Parts.Count][]; - for (var index = 0; index < manifest.Parts.Count; index++) - { - var expected = manifest.Parts[index]; - if (!partsByName.TryGetValue(expected.Name, out var partFile)) - throw new InvalidDataException($"云端备份缺少第 {expected.Index} 个分片。"); - parts[index] = await cloudClient.DownloadAsync(partFile.FileId, cancellationToken).ConfigureAwait(false); - } - - var archive = CloudBackupPackage.MergeAndVerify(manifest, parts); - var archivePath = GetCloudCachePath($"{descriptor.BackupId}.zip"); - await File.WriteAllBytesAsync(archivePath, archive, cancellationToken).ConfigureAwait(false); - logger.LogInformation("云端备份已下载并校验:备份={BackupId},分片={Parts},大小={Bytes}。", - descriptor.BackupId, manifest.Parts.Count, archive.LongLength); - return archivePath; - } - - /// - /// Deletes every part of one backup and the manifest only after all parts are gone, so an - /// interrupted delete stays visible as an incomplete backup that can be retried. - /// - public async Task DeleteAsync(CloudBackupDescriptor descriptor, CancellationToken cancellationToken = default) - { - ArgumentNullException.ThrowIfNull(descriptor); - var owned = await FindBackupFilesAsync(descriptor.BackupId, cancellationToken).ConfigureAwait(false); - var failures = 0; - foreach (var part in owned.Where(file => !IsManifest(file.FileName))) - failures += await TryDeleteAsync(part, cancellationToken).ConfigureAwait(false); - - if (failures == 0) - { - foreach (var manifest in owned.Where(file => IsManifest(file.FileName))) - failures += await TryDeleteAsync(manifest, cancellationToken).ConfigureAwait(false); - } - - if (failures > 0) - throw new SectlCloudStorageException("delete_failed", "部分云端备份文件删除失败,请稍后重试。"); - logger.LogInformation("云端备份已删除:备份={BackupId},文件数={Files}。", descriptor.BackupId, owned.Count); - } - - /// Removes every backup group that has no manifest or is missing parts. - public async Task PurgeIncompleteAsync(CancellationToken cancellationToken = default) - { - var descriptors = await ListAsync(cancellationToken).ConfigureAwait(false); - var removed = 0; - foreach (var descriptor in descriptors.Where(item => !item.IsComplete)) - { - await DeleteAsync(descriptor, cancellationToken).ConfigureAwait(false); - removed++; - } - - return removed; - } - - /// - /// Newest upload time among this device's own backups, so the automatic cadence is per device - /// and another signed-in machine's uploads do not postpone this one. Null means this device has - /// not uploaded yet. - /// - public async Task GetLatestOwnBackupTimeAsync(CancellationToken cancellationToken = default) - { - if (DeviceTag.Length == 0) - return null; - - var backups = await ListAsync(cancellationToken).ConfigureAwait(false); - return backups - .Where(IsOwnBackup) - .Select(backup => backup.CreatedAt) - .Max(); - } - - /// - /// Cloud state is never cached, so the oldest backup is rediscovered from the account on - /// every attempt; orders newest first. Quota pressure is the one - /// deletion that deliberately crosses device boundaries. - /// - private async Task FindOldestAsync(CancellationToken cancellationToken) - { - var backups = await ListAsync(cancellationToken).ConfigureAwait(false); - return backups.Count == 0 ? null : backups[^1]; - } - - /// Keeps at most of this device's own backups. - private async Task TrimAsync(int maximumBackups, CancellationToken cancellationToken) - { - if (maximumBackups <= 0 || DeviceTag.Length == 0) - return; - - var backups = await ListAsync(cancellationToken).ConfigureAwait(false); - foreach (var expired in backups.Where(IsOwnBackup).Skip(maximumBackups)) - { - logger.LogInformation("云端备份超过保留上限,删除本设备最早的备份:备份={BackupId}。", expired.BackupId); - await DeleteAsync(expired, cancellationToken).ConfigureAwait(false); - } - } - - private async Task> FindBackupFilesAsync(string backupId, - CancellationToken cancellationToken) - { - var files = await cloudClient.ListFilesAsync(cancellationToken).ConfigureAwait(false); - return files.Where(file => - CloudBackupPackage.TryParseFileName(file.FileName, out var fileBackupId, out _, out _, out _) && - string.Equals(fileBackupId, backupId, StringComparison.Ordinal)) - .ToArray(); - } - - private async Task TryDeleteAsync(SectlCloudFile file, CancellationToken cancellationToken) - { - try - { - await cloudClient.DeleteAsync(file.FileId, file.FileDocumentId, cancellationToken).ConfigureAwait(false); - return 0; - } - catch (OperationCanceledException) - { - throw; - } - catch (Exception exception) - { - logger.LogWarning(exception, "删除云端备份文件失败:文件={FileName}", file.FileName); - return 1; - } - } - - private async Task RollbackAsync(IReadOnlyList uploaded) - { - if (uploaded.Count == 0) - return; - - logger.LogWarning("云端备份上传未完成,正在清理已上传的分片:数量={Count}", uploaded.Count); - foreach (var file in uploaded) - { - // Cleanup must not be cancelled by the failure that triggered it. - await TryDeleteAsync(file, CancellationToken.None).ConfigureAwait(false); - } - } - - private static IReadOnlyList GroupBackups(IReadOnlyList files) - { - var groups = new Dictionary(StringComparer.Ordinal); - foreach (var file in files) - { - if (!CloudBackupPackage.TryParseFileName(file.FileName, out var backupId, out var partIndex, out var partCount, - out var isManifest, out var isEncrypted)) - continue; - if (!groups.TryGetValue(backupId, out var group)) - { - group = new BackupGroup(backupId); - groups[backupId] = group; - } - - if (isManifest) - group.Manifest = file; - else - group.Parts[partIndex] = file; - group.DeclaredPartCount = Math.Max(group.DeclaredPartCount, partCount); - group.IsEncrypted |= isEncrypted; - } - - return groups.Values - .Select(group => group.ToDescriptor()) - .OrderByDescending(descriptor => descriptor.CreatedAt ?? DateTimeOffset.MinValue) - .ThenByDescending(descriptor => descriptor.BackupId, StringComparer.Ordinal) - .ToArray(); - } - - private static bool IsManifest(string fileName) => - CloudBackupPackage.TryParseFileName(fileName, out _, out _, out _, out var isManifest) && isManifest; - - /// - /// Alias stamped on this device's uploads: the configured alias when set, otherwise the device - /// label the platform head supplies, otherwise the host name. Android and iOS report - /// localhost as their host name, so the head's label is what keeps two phones from - /// sharing one alias — and with it one retention bucket. The alias is a user-visible display - /// label, not a device identity: the device UUID stays out of every cloud archive and restore. - /// - private string ResolveDeviceTag() - { - var configured = configHandler.Data.General.Backup.CloudDeviceAlias; - var deviceName = !string.IsNullOrWhiteSpace(configured) - ? configured - : (platform as MobilePlatformServiceRoot)?.DeviceName is { Length: > 0 } platformName - ? platformName - : Environment.MachineName; - return CloudBackupPackage.BuildDeviceTag(deviceName); - } - - /// Backup list label: the id, plus the device alias when the id carries one. - private static string BuildDisplayName(string backupId, string deviceTag) => - deviceTag.Length == 0 ? backupId : $"{backupId} ({deviceTag})"; - - private static string GetCloudCachePath(string fileName) => - Utils.GetFilePath("cache", "cloud-backup", fileName); - - private static void TryDeleteFile(string path) - { - try - { - if (File.Exists(path)) - File.Delete(path); - } - catch (IOException) - { - // A leftover staging archive is harmless and stays outside every archive root. - } - catch (UnauthorizedAccessException) - { - } - } - - private sealed class BackupGroup(string backupId) - { - public string BackupId { get; } = backupId; - public SectlCloudFile? Manifest { get; set; } - public SortedDictionary Parts { get; } = new(); - public int DeclaredPartCount { get; set; } - - /// - /// Taken from the file names, so the listing can flag a package the removed encryption - /// feature uploaded without downloading a manifest per backup. - /// - public bool IsEncrypted { get; set; } - - public CloudBackupDescriptor ToDescriptor() - { - var isComplete = Manifest is not null && Parts.Count > 0 && DeclaredPartCount > 0 && - Parts.Count == DeclaredPartCount && - Enumerable.Range(1, DeclaredPartCount).All(Parts.ContainsKey); - var size = Parts.Values.Sum(part => part.Size); - var created = Manifest?.CreatedAt ?? Parts.Values - .Select(part => part.CreatedAt) - .Where(timestamp => timestamp.HasValue) - .OrderByDescending(timestamp => timestamp) - .FirstOrDefault(); - var deviceTag = CloudBackupPackage.TryGetDeviceTag(BackupId, out var tag) ? tag : string.Empty; - return new CloudBackupDescriptor(BackupId, BuildDisplayName(BackupId, deviceTag), created, - size, Parts.Count, isComplete, Manifest?.FileId, deviceTag, IsEncrypted); - } - } -} diff --git a/SecRandom/Services/ImportExport/IImportExportService.cs b/SecRandom/Services/ImportExport/IImportExportService.cs index bd73dee42..910b2224c 100644 --- a/SecRandom/Services/ImportExport/IImportExportService.cs +++ b/SecRandom/Services/ImportExport/IImportExportService.cs @@ -11,16 +11,11 @@ Task ExportDiagnosticAsync(string destinationPath, bool includeExtendedD CancellationToken cancellationToken = default); Task ExportSettingsAsync(string destinationPath, CancellationToken cancellationToken = default); Task ExportAllDataAsync(string destinationPath, CancellationToken cancellationToken = default); - Task ExportCloudBackupAsync(string destinationPath, CancellationToken cancellationToken = default); - /// Cloud archive root set the current cloud backup-content selection resolves to. - IReadOnlyList GetCloudBackupRoots(); Task InspectSettingsAsync(string sourcePath, CancellationToken cancellationToken = default); Task InspectAllDataAsync(string sourcePath, CancellationToken cancellationToken = default); - Task InspectCloudBackupAsync(string sourcePath, CancellationToken cancellationToken = default); Task ImportSettingsAsync(string sourcePath, CancellationToken cancellationToken = default); Task ImportAllDataAsync(string sourcePath, CancellationToken cancellationToken = default); - Task ImportCloudBackupAsync(string sourcePath, CancellationToken cancellationToken = default); string CreateManualBackup(IReadOnlyCollection roots); string CreateAutomaticBackup(CancellationToken cancellationToken = default); Task RestoreBackupAsync(string sourcePath, CancellationToken cancellationToken = default); diff --git a/SecRandom/Services/ImportExport/ImportExportService.cs b/SecRandom/Services/ImportExport/ImportExportService.cs index f45feca9c..6d90ac146 100644 --- a/SecRandom/Services/ImportExport/ImportExportService.cs +++ b/SecRandom/Services/ImportExport/ImportExportService.cs @@ -9,7 +9,7 @@ using Microsoft.Extensions.Logging; using SecRandom.Core; using SecRandom.Core.Abstraction; -using SecRandom.Core.Abstraction.Services; +using SecRandom.Core.Abstraction.Services; using SecRandom.Core.Helpers; using SecRandom.Core.Services.Archive; using SecRandom.Core.Services.Config; @@ -25,7 +25,7 @@ namespace SecRandom.Services.ImportExport; public sealed class ImportExportService( MainConfigHandler configHandler, DataArchiveService dataArchiveService, - IHistoryQueryService historyQuery, + IHistoryQueryService historyQuery, ILogger logger) : IImportExportService { private readonly string _dataDirectory = Utils.DataRoot; @@ -40,13 +40,6 @@ public Task ExportAllDataAsync(string destinationPath, CancellationToken return dataArchiveService.ExportAllDataAsync(destinationPath, cancellationToken); } - public Task ExportCloudBackupAsync(string destinationPath, CancellationToken cancellationToken = default) - { - return dataArchiveService.ExportCloudBackupAsync(destinationPath, cancellationToken); - } - - public IReadOnlyList GetCloudBackupRoots() => dataArchiveService.GetCloudBackupRoots(); - public Task InspectSettingsAsync(string sourcePath, CancellationToken cancellationToken = default) { return dataArchiveService.InspectSettingsAsync(sourcePath, cancellationToken); @@ -57,11 +50,6 @@ public Task InspectAllDataAsync(string sourcePath, Cancellatio return dataArchiveService.InspectAllDataAsync(sourcePath, cancellationToken); } - public Task InspectCloudBackupAsync(string sourcePath, CancellationToken cancellationToken = default) - { - return dataArchiveService.InspectCloudBackupAsync(sourcePath, cancellationToken); - } - public Task ImportSettingsAsync(string sourcePath, CancellationToken cancellationToken = default) { return dataArchiveService.ImportSettingsAsync(sourcePath, cancellationToken); @@ -72,11 +60,6 @@ public Task ImportAllDataAsync(string sourcePath, CancellationToke return dataArchiveService.ImportAllDataAsync(sourcePath, cancellationToken); } - public Task ImportCloudBackupAsync(string sourcePath, CancellationToken cancellationToken = default) - { - return dataArchiveService.ImportCloudBackupAsync(sourcePath, cancellationToken); - } - public string CreateManualBackup(IReadOnlyCollection roots) { return dataArchiveService.CreateManualBackup(roots); @@ -163,9 +146,9 @@ private void AddExtendedDiagnosticData(ZipArchive archive, List new(null, false, [], 0, null, null, null, null, true); public static SecurityCredentialMetadata CreateInvalid() => new(null, false, [], 0, null, null, null, null, false); @@ -557,9 +554,6 @@ internal sealed class SecurityCredentialMetadata( public string? Ciphertext { get; set; } = ciphertext; public bool IsReadable { get; } = isReadable; - /// settings.json 的整份文件指纹记录;为 null 表示未开启防篡改校验。 - public SettingsIntegrityRecord? SettingsIntegrity { get; set; } = settingsIntegrity; - private static UsbBindingCredential CloneBinding(UsbBindingCredential binding) { return new UsbBindingCredential @@ -605,24 +599,9 @@ internal sealed class SecurityCredentialEnvelope public required string Nonce { get; init; } public required string Tag { get; init; } public required string Ciphertext { get; init; } - public SettingsIntegrityRecord? SettingsIntegrity { get; init; } } -/// -/// settings.json 的整份文件指纹记录。它与锁定状态同级存放在凭据信封的明文部分, -/// 因此无需主密码即可刷新和校验;代价是能改凭据文件的人也能改这份指纹, -/// 所以它属于"防误改、防普通用户"级别的保护,而不是密码学意义上的防伪。 -/// -internal sealed class SettingsIntegrityRecord -{ - public const int CurrentFormatVersion = 1; - public int FormatVersion { get; init; } = CurrentFormatVersion; - public required string Digest { get; init; } - public DateTimeOffset RecordedAtUtc { get; init; } - public string? RecordedAppVersion { get; init; } - public long Generation { get; init; } -} internal sealed record SecurityCredentialAuthenticationData( int FormatVersion, diff --git a/SecRandom/Services/Security/SecurityService.cs b/SecRandom/Services/Security/SecurityService.cs index 74d7a40d3..c8e039a8c 100644 --- a/SecRandom/Services/Security/SecurityService.cs +++ b/SecRandom/Services/Security/SecurityService.cs @@ -11,7 +11,6 @@ using SecRandom.Core.Enums.Configs; using SecRandom.Core.Models.SubConfigs; using SecRandom.Platforms.Abstractions; -using IntegrityAction = SecRandom.Core.Enums.Configs.SettingsIntegrityAction; namespace SecRandom.Services.Security; @@ -1100,9 +1099,6 @@ private readonly record struct SecuritySettingsSnapshot( bool ProtectLotteryStart, bool ProtectLotteryReset, bool ProtectLinkage, - bool SettingsIntegrityCheckEnabled, - SettingsIntegrityAction SettingsIntegrityAction, - SettingsIntegrityRestoreSource SettingsIntegrityRestoreSource, int SudoModeDurationSeconds, bool SudoModeEnabled) { @@ -1125,9 +1121,6 @@ private readonly record struct SecuritySettingsSnapshot( settings.ProtectLotteryStart, settings.ProtectLotteryReset, settings.ProtectLinkage, - settings.SettingsIntegrityCheckEnabled, - settings.SettingsIntegrityAction, - settings.SettingsIntegrityRestoreSource, settings.SudoModeDurationSeconds, settings.SudoModeEnabled); public void Restore(SecuritySettingsConfig settings) @@ -1150,9 +1143,6 @@ public void Restore(SecuritySettingsConfig settings) settings.ProtectLotteryStart = ProtectLotteryStart; settings.ProtectLotteryReset = ProtectLotteryReset; settings.ProtectLinkage = ProtectLinkage; - settings.SettingsIntegrityCheckEnabled = SettingsIntegrityCheckEnabled; - settings.SettingsIntegrityAction = SettingsIntegrityAction; - settings.SettingsIntegrityRestoreSource = SettingsIntegrityRestoreSource; settings.SudoModeDurationSeconds = SudoModeDurationSeconds; settings.SudoModeEnabled = SudoModeEnabled; } @@ -1168,9 +1158,6 @@ public bool IsProtectionDowngrade(SecuritySettingsSnapshot after) => || Removed(UsbBindingEnabled, after.UsbBindingEnabled) || Removed(RequireAllSelectedFactors, after.RequireAllSelectedFactors) || Added(AllowSettingsPreview, after.AllowSettingsPreview) - || Removed(SettingsIntegrityCheckEnabled, after.SettingsIntegrityCheckEnabled) - || (SettingsIntegrityAction == IntegrityAction.Confirm && - after.SettingsIntegrityAction == IntegrityAction.AutoRestore) || Removed(ProtectOpenSettings, after.ProtectOpenSettings) || Removed(ProtectToggleMainWindow, after.ProtectToggleMainWindow) || Removed(ProtectToggleFloatingWindow, after.ProtectToggleFloatingWindow) @@ -1214,15 +1201,12 @@ private void NormalizeSettings(SecurityCredentials credentials) DisableOperationProtections(); } - // 防篡改校验属于安全保护的一部分,保护关闭时一并关闭 - if (!Settings.SecurityEnabled) - Settings.SettingsIntegrityCheckEnabled = false; + } private void DisableOperationProtections() { - // 防篡改校验以安全凭据为锚点,保护被整体关闭时它也不再成立 - Settings.SettingsIntegrityCheckEnabled = false; + Settings.ProtectOpenSettings = false; Settings.ProtectToggleMainWindow = false; Settings.ProtectToggleFloatingWindow = false; @@ -1440,9 +1424,7 @@ private void NormalizeSettings(SecurityCredentialMetadata metadata) DisableOperationProtections(); } - // 防篡改校验属于安全保护的一部分,保护关闭时一并关闭 - if (!Settings.SecurityEnabled) - Settings.SettingsIntegrityCheckEnabled = false; + } private void TryDeleteUsbKeyAtPath(string rootPath) diff --git a/SecRandom/Services/Security/SecuritySettingsStore.cs b/SecRandom/Services/Security/SecuritySettingsStore.cs index 94e6ef424..f21e52cea 100644 --- a/SecRandom/Services/Security/SecuritySettingsStore.cs +++ b/SecRandom/Services/Security/SecuritySettingsStore.cs @@ -194,14 +194,11 @@ private void ScrubLegacyPlaintext(MainConfigHandler handler) /// /// 最严的一档:防护总开关打开、所有受保护操作打开。因素开关不在这里预置,它们由凭据推导。 - /// 防篡改校验不在这里打开——那是用户明确选择的功能,不能替用户打开。 /// private static SecuritySettingsConfig CreateProtectiveDefaults() => new() { SecurityEnabled = true, SudoModeEnabled = true, - SettingsIntegrityAction = SettingsIntegrityAction.Confirm, - SettingsIntegrityRestoreSource = SettingsIntegrityRestoreSource.Local, ProtectOpenSettings = true, ProtectToggleMainWindow = true, ProtectToggleFloatingWindow = true, diff --git a/SecRandom/Services/Security/SettingsIntegrityCommandGate.cs b/SecRandom/Services/Security/SettingsIntegrityCommandGate.cs deleted file mode 100644 index 20dde0d29..000000000 --- a/SecRandom/Services/Security/SettingsIntegrityCommandGate.cs +++ /dev/null @@ -1,16 +0,0 @@ -namespace SecRandom.Services.Security; - -public static class SettingsIntegrityCommandGate -{ - public static bool IsAllowed(bool confirmationPending) => !confirmationPending; - - public static bool TryRun(bool confirmationPending, Action command) - { - ArgumentNullException.ThrowIfNull(command); - if (!IsAllowed(confirmationPending)) - return false; - - command(); - return true; - } -} diff --git a/SecRandom/Services/Security/SettingsIntegrityRecoveryService.cs b/SecRandom/Services/Security/SettingsIntegrityRecoveryService.cs deleted file mode 100644 index a04f36b89..000000000 --- a/SecRandom/Services/Security/SettingsIntegrityRecoveryService.cs +++ /dev/null @@ -1,460 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.IO.Compression; -using System.Linq; -using System.Text.Json; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.Extensions.Logging; -using SecRandom.Core.Abstraction; -using SecRandom.Core.Enums.Configs; -using SecRandom.Core.Models; -using SecRandom.Core.Services.Config; -using SecRandom.Services.ImportExport; -using SecRandom.Shared; - -namespace SecRandom.Services.Security; - -internal enum SettingsIntegrityRecoveryStatus -{ - Succeeded, - NoBackupAvailable, - CloudNotSignedIn, - Failed -} - -/// -/// 自动恢复的结果。 只承载技术原因(文件名、异常消息等), -/// 面向用户的文案由调用方按状态选择本地化资源。 -/// -internal sealed record SettingsIntegrityRecoveryResult( - SettingsIntegrityRecoveryStatus Status, - bool FromCloud, - string? BackupName, - string? PreRestorePath, - string? Detail) -{ - public bool Succeeded => Status == SettingsIntegrityRecoveryStatus.Succeeded; -} - -/// -/// 设置文件防篡改校验发现改动后的自动恢复。按配置的来源顺序找到最近一次包含 -/// config/settings.json 的备份,先把当前文件另存为「恢复前」副本,再用备份内容 -/// 原子替换,最后重载配置以刷新指纹记录。只处理设置文件本身,名单、历史等其他数据不变; -/// 任何一步失败都保留原文件,让启动流程回退到安全密码确认闸门。 -/// -/// 恢复只使用本机自己的备份:本地 data/backup 归档,以及本机上传到账号云端的备份。 -/// 另一台设备上传的云端备份描述的是那台机器的配置,永远不会被用来自动恢复本机设置文件。 -/// -/// -internal sealed class SettingsIntegrityRecoveryService -{ - internal const string SettingsEntryPath = "config/settings.json"; - private const string PreRestoreDirectoryName = "integrity"; - - private readonly MainConfigHandler _configHandler; - private readonly SecuritySettingsStore _securitySettings; - private readonly IImportExportService _importExportService; - private readonly ILogger _logger; - private readonly string? _configFilePath; - private readonly string? _backupDirectory; - - public SettingsIntegrityRecoveryService( - MainConfigHandler configHandler, - SecuritySettingsStore securitySettings, - IImportExportService importExportService, - ILogger logger, - string? configFilePath = null, - string? backupDirectory = null) - { - _configHandler = configHandler; - _securitySettings = securitySettings; - _importExportService = importExportService; - _logger = logger; - _configFilePath = configFilePath; - _backupDirectory = backupDirectory; - } - - private string ConfigFilePath => _configFilePath ?? _configHandler.Data.ConfigFilePath; - private string BackupDirectory => _backupDirectory ?? Utils.GetDirectoryPath("backup"); - - public async Task TryRecoverAsync(CancellationToken cancellationToken = default) - { - var source = _securitySettings.Data.SettingsIntegrityRestoreSource; - var cloudPreferred = source == SettingsIntegrityRestoreSource.CloudThenLocal; - SettingsIntegrityRecoveryResult? failure = null; - - try - { - foreach (var attempt in ResolveAttemptOrder(source)) - { - cancellationToken.ThrowIfCancellationRequested(); - var result = attempt == RecoverySourceKind.Cloud - ? await TryRecoverFromCloudAsync(cancellationToken).ConfigureAwait(false) - : await TryRecoverFromLocalAsync(cancellationToken).ConfigureAwait(false); - if (result.Succeeded) - return result; - - failure = PreferredFailure(failure, result, cloudPreferred); - } - } - catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) - { - throw; - } - catch (Exception exception) - { - // 启动闸门不能让恢复流程本身的异常冒泡,否则用户既没恢复也没得到确认入口。 - _logger.LogError(exception, "设置文件自动恢复时发生未预期的错误。"); - return Failed(false, Describe(exception)); - } - - var resolved = failure ?? NoBackup(); - _logger.LogWarning("设置文件自动恢复未完成:状态={Status},原因={Detail}。", resolved.Status, resolved.Detail); - return resolved; - } - - /// - /// 来源顺序与设置卡一一对应:仅本地、本地优先云端补全、云端优先本地兜底。 - /// - private static RecoverySourceKind[] ResolveAttemptOrder(SettingsIntegrityRestoreSource source) => - source switch - { - SettingsIntegrityRestoreSource.LocalThenCloud => [RecoverySourceKind.Local, RecoverySourceKind.Cloud], - SettingsIntegrityRestoreSource.CloudThenLocal => [RecoverySourceKind.Cloud, RecoverySourceKind.Local], - _ => [RecoverySourceKind.Local] - }; - - /// - /// 云端候选只保留本机上传的备份,组内按上传时间从新到旧。设置文件描述的是它所在的那台机器, - /// 另一台设备的备份既不是本机的配置,也不能当作本机备份的兜底,所以它永远不会成为候选: - /// 本机没有自己的可用备份时宁可不恢复,退回本地备份或安全密码闸门。 - /// 设备别名为空(主机名无法生成安全别名)时没有本机组,因此没有任何云端候选。 - /// - internal static IReadOnlyList OrderCloudCandidates( - IEnumerable backups, string? deviceTag) => - backups.Where(item => item.CanRestore) - .Where(item => CloudBackupService.IsOwnBackup(item, deviceTag ?? string.Empty)) - .OrderByDescending(item => item.CreatedAt ?? DateTimeOffset.MinValue) - .ToArray(); - - /// - /// 失败信息展示最有用的那条:真实的文件/恢复错误优先于「没有可用备份」,而「未登录账号」 - /// 只在用户明确选择云端优先时才有意义。 - /// - private static SettingsIntegrityRecoveryResult PreferredFailure( - SettingsIntegrityRecoveryResult? current, - SettingsIntegrityRecoveryResult candidate, - bool cloudPreferred) - { - if (current is null) - return candidate; - - var currentPriority = FailurePriority(current.Status, cloudPreferred); - var candidatePriority = FailurePriority(candidate.Status, cloudPreferred); - return candidatePriority > currentPriority ? candidate : current; - } - - private static int FailurePriority(SettingsIntegrityRecoveryStatus status, bool cloudPreferred) => - status switch - { - SettingsIntegrityRecoveryStatus.Failed => 3, - SettingsIntegrityRecoveryStatus.CloudNotSignedIn => cloudPreferred ? 2 : 1, - _ => 1 - }; - - private async Task TryRecoverFromLocalAsync(CancellationToken cancellationToken) - { - var directory = new DirectoryInfo(BackupDirectory); - if (!directory.Exists) - return NoBackup(); - - string? lastDetail = null; - // 备份页只展示 *.zip;恢复只认同一批归档,并按创建时间从新到旧尝试。 - foreach (var file in directory.EnumerateFiles("*.zip").OrderByDescending(file => file.CreationTimeUtc)) - { - cancellationToken.ThrowIfCancellationRequested(); - if (!await IsSupportedArchiveAsync(file.FullName, false, cancellationToken).ConfigureAwait(false)) - { - lastDetail = file.Name; - continue; - } - - if (!TryReadSettingsEntry(file.FullName, out var payload, out var readError)) - { - lastDetail = readError; - continue; - } - - if (!IsLoadableSettingsPayload(payload)) - { - // 坏备份只跳过这一个候选,不能让最近一次备份的损坏内容阻断更早的可用备份。 - lastDetail = file.Name; - continue; - } - - if (TryCommitRestoredSettings(payload, out var preRestorePath, out var commitError)) - return Succeeded(false, file.Name, preRestorePath); - - return Failed(false, commitError); - } - - return NoBackup(lastDetail); - } - - private async Task TryRecoverFromCloudAsync(CancellationToken cancellationToken) - { - var cloud = IAppHost.TryGetService(); - if (cloud is null || !cloud.IsSignedIn) - return new SettingsIntegrityRecoveryResult( - SettingsIntegrityRecoveryStatus.CloudNotSignedIn, true, null, null, null); - - IReadOnlyList backups; - try - { - backups = await cloud.ListAsync(cancellationToken).ConfigureAwait(false); - } - catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) - { - throw; - } - catch (Exception exception) - { - _logger.LogWarning(exception, "列出云端备份失败,尝试其它来源。"); - return Failed(true, Describe(exception)); - } - - // 只认本机上传的备份:其他设备的备份是那台机器的配置,本机没有自己的可用备份时宁可不恢复, - // 也不能拿别的设备的设置来覆盖本机。 - var candidates = OrderCloudCandidates(backups, cloud.DeviceTag); - if (candidates.Count == 0 && backups.Any(item => item.CanRestore)) - { - _logger.LogWarning("云端没有本机上传的可用备份,其他设备的备份不用于设置文件恢复:云端可用备份={Count}。", - backups.Count(item => item.CanRestore)); - } - - string? lastDetail = null; - foreach (var descriptor in candidates) - { - cancellationToken.ThrowIfCancellationRequested(); - string archivePath; - try - { - archivePath = await cloud.DownloadAsync(descriptor, cancellationToken).ConfigureAwait(false); - } - catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) - { - throw; - } - catch (Exception exception) - { - _logger.LogWarning(exception, "下载云端备份失败:备份={BackupId}。", descriptor.BackupId); - lastDetail = Describe(exception); - continue; - } - - try - { - if (!await IsSupportedArchiveAsync(archivePath, true, cancellationToken).ConfigureAwait(false)) - { - lastDetail = descriptor.DisplayName; - continue; - } - - if (!TryReadSettingsEntry(archivePath, out var payload, out var readError)) - { - lastDetail = readError; - continue; - } - - if (!IsLoadableSettingsPayload(payload)) - { - lastDetail = descriptor.DisplayName; - continue; - } - - if (TryCommitRestoredSettings(payload, out var preRestorePath, out var commitError)) - return Succeeded(true, descriptor.DisplayName, preRestorePath); - - return Failed(true, commitError); - } - finally - { - TryDeleteFile(archivePath); - } - } - - return NoBackup(lastDetail); - } - - /// - /// 备份必须先是受支持的 v3 归档;data/backup 里被替换成任意 ZIP 的文件不会被当作恢复来源。 - /// - private async Task IsSupportedArchiveAsync(string archivePath, bool cloudArchive, - CancellationToken cancellationToken) - { - try - { - var inspection = cloudArchive - ? await _importExportService.InspectCloudBackupAsync(archivePath, cancellationToken).ConfigureAwait(false) - : await _importExportService.InspectAllDataAsync(archivePath, cancellationToken).ConfigureAwait(false); - return inspection.IsSupportedV3; - } - catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) - { - throw; - } - catch (Exception exception) - { - _logger.LogWarning(exception, "备份归档校验失败:文件={FileName}。", Path.GetFileName(archivePath)); - return false; - } - } - - private bool TryReadSettingsEntry(string archivePath, out byte[] payload, out string? error) - { - payload = []; - error = null; - try - { - using var archive = ZipFile.OpenRead(archivePath); - var entry = archive.Entries.FirstOrDefault(item => - string.Equals(item.FullName.Replace('\\', '/'), SettingsEntryPath, StringComparison.OrdinalIgnoreCase)); - if (entry is null) - { - error = Path.GetFileName(archivePath); - return false; - } - - using var stream = entry.Open(); - using var buffer = new MemoryStream(); - stream.CopyTo(buffer); - payload = buffer.ToArray(); - return true; - } - catch (Exception exception) - { - _logger.LogWarning(exception, "读取备份中的设置文件失败:文件={FileName}。", Path.GetFileName(archivePath)); - error = Describe(exception); - return false; - } - } - - /// - /// 用备份内容替换设置文件:先写恢复前副本,再原子替换并重载配置;重载失败时回滚原文件, - /// 保证「恢复失败」不会让用户同时失去当前文件和旧指纹。 - /// - private bool TryCommitRestoredSettings(byte[] payload, out string? preRestorePath, out string? error) - { - preRestorePath = null; - error = null; - var configPath = ConfigFilePath; - byte[]? previous = null; - try - { - if (File.Exists(configPath)) - { - previous = File.ReadAllBytes(configPath); - preRestorePath = CreatePreRestorePath(); - WriteAtomic(preRestorePath, previous); - } - - WriteAtomic(configPath, payload); - try - { - _configHandler.Reload(); - } - catch - { - if (previous is not null) - WriteAtomic(configPath, previous); - throw; - } - - _logger.LogInformation("设置文件已从备份恢复:恢复前副本={PreRestorePath}。", preRestorePath ?? string.Empty); - return true; - } - catch (Exception exception) - { - _logger.LogError(exception, "写入恢复后的设置文件失败。"); - error = Describe(exception); - preRestorePath = null; - return false; - } - } - - /// - /// 恢复内容必须仍是可用的设置文件;空对象、非对象或无法反序列化的内容一律拒绝, - /// 否则一次坏备份会静默把用户配置重置成默认值。 - /// - private static bool IsLoadableSettingsPayload(byte[] payload) - { - if (payload.Length == 0) - return false; - - try - { - using var document = JsonDocument.Parse(payload); - var root = document.RootElement; - if (root.ValueKind != JsonValueKind.Object || !root.EnumerateObject().Any()) - return false; - - return JsonSerializer.Deserialize(payload, ConfigServiceBase.JsonOptions) is not null; - } - catch (JsonException) - { - return false; - } - } - - private string CreatePreRestorePath() - { - var directory = Path.Combine(BackupDirectory, PreRestoreDirectoryName); - Directory.CreateDirectory(directory); - return Path.Combine(directory, $"settings_before_restore_{DateTime.Now:yyyyMMdd_HHmmss}.json"); - } - - private static void WriteAtomic(string path, byte[] content) - { - var directory = Path.GetDirectoryName(path); - if (!string.IsNullOrWhiteSpace(directory)) - Directory.CreateDirectory(directory); - - var temporaryPath = $"{path}.{Guid.NewGuid():N}.tmp"; - File.WriteAllBytes(temporaryPath, content); - File.Move(temporaryPath, path, overwrite: true); - } - - private static SettingsIntegrityRecoveryResult Succeeded(bool fromCloud, string backupName, - string? preRestorePath) => - new(SettingsIntegrityRecoveryStatus.Succeeded, fromCloud, backupName, preRestorePath, null); - - private static SettingsIntegrityRecoveryResult NoBackup(string? detail = null) => - new(SettingsIntegrityRecoveryStatus.NoBackupAvailable, false, null, null, detail); - - private static SettingsIntegrityRecoveryResult Failed(bool fromCloud, string? detail) => - new(SettingsIntegrityRecoveryStatus.Failed, fromCloud, null, null, detail); - - private static string Describe(Exception exception) => - string.IsNullOrWhiteSpace(exception.Message) ? exception.GetType().Name : exception.Message; - - private static void TryDeleteFile(string path) - { - try - { - if (File.Exists(path)) - File.Delete(path); - } - catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) - { - // 缓存文件残留不影响恢复结果。 - } - } - - private enum RecoverySourceKind - { - Local, - Cloud - } -} diff --git a/SecRandom/Services/Security/SettingsIntegrityService.cs b/SecRandom/Services/Security/SettingsIntegrityService.cs deleted file mode 100644 index 1993a7e82..000000000 --- a/SecRandom/Services/Security/SettingsIntegrityService.cs +++ /dev/null @@ -1,155 +0,0 @@ -using System; -using System.IO; -using System.Security.Cryptography; -using Microsoft.Extensions.Logging; -using SecRandom.Core; -using SecRandom.Core.Services.Config; - -namespace SecRandom.Services.Security; - -/// -/// settings.json 整份文件的防篡改校验。 -/// 开启后,每次配置写盘都会把「整份文件哈希 + 记录时间 + 程序版本 + 序号」写进安全凭据 -/// 信封的明文部分,启动时再比对文件哈希;不一致即说明该文件在上次记录之后被程序之外的 -/// 东西改过。指纹依赖凭据文件作为锚点,未设置安全密码时该功能不生效。 -/// -internal sealed class SettingsIntegrityService -{ - private readonly MainConfigHandler _configHandler; - private readonly SecuritySettingsStore _securitySettings; - private readonly SecurityCredentialStore _credentialStore; - private readonly ILogger _logger; - private readonly string? _configFilePath; - - public SettingsIntegrityService( - MainConfigHandler configHandler, - SecuritySettingsStore securitySettings, - SecurityCredentialStore credentialStore, - ILogger logger, - string? configFilePath = null) - { - _configHandler = configHandler; - _securitySettings = securitySettings; - _credentialStore = credentialStore; - _logger = logger; - _configFilePath = configFilePath; - configHandler.Saved += OnConfigWritten; - configHandler.Reloaded += OnConfigWritten; - // 防篡改开关自己住在加密的安全设置里:开关它的那一次写入不会再碰 settings.json, - // 所以这里必须同样订阅安全设置,否则"打开校验"之后永远不会有指纹记录。 - securitySettings.Saved += OnConfigWritten; - } - - private string ConfigFilePath => _configFilePath ?? _configHandler.Data.ConfigFilePath; - - /// 是否存在指纹记录,即防篡改校验是否已开启且凭据可用。 - public bool IsEnabled => _credentialStore.LoadMetadata().SettingsIntegrity is not null; - - /// - /// 返回本次启动检测到的「设置文件与记录不符」,没有记录或校验通过时返回 null。 - /// - public SettingsIntegrityMismatch? GetPendingMismatch() - { - var record = _credentialStore.LoadMetadata().SettingsIntegrity; - if (record is null) - return null; - - var digest = TryComputeDigest(out var lastWriteTimeUtc); - if (digest is not null && string.Equals(digest, record.Digest, StringComparison.Ordinal)) - return null; - - _logger.LogWarning( - "Settings integrity check failed: the settings file does not match its recorded fingerprint."); - return new SettingsIntegrityMismatch(record.RecordedAtUtc, record.RecordedAppVersion, lastWriteTimeUtc); - } - - /// - /// 以当前磁盘内容为准刷新指纹;设置项已关闭或没有可写锚点时清除指纹。 - /// - public void AcceptCurrentFile() - { - try - { - var metadata = _credentialStore.LoadMetadata(); - if (metadata.Password is null) - return; - - if (!_securitySettings.Data.SettingsIntegrityCheckEnabled) - { - ClearRecord(metadata); - return; - } - - var digest = TryComputeDigest(out _); - if (digest is null) - { - _logger.LogWarning( - "Settings integrity fingerprint cannot be recorded because the settings file is unavailable."); - ClearRecord(metadata); - return; - } - - if (metadata.SettingsIntegrity is { } current && string.Equals(current.Digest, digest, StringComparison.Ordinal)) - return; - - metadata.SettingsIntegrity = new SettingsIntegrityRecord - { - Digest = digest, - RecordedAtUtc = DateTimeOffset.UtcNow, - RecordedAppVersion = GlobalConstants.Version, - Generation = (metadata.SettingsIntegrity?.Generation ?? 0) + 1 - }; - _credentialStore.SaveMetadata(metadata); - } - catch (Exception exception) when (IsPersistenceFailure(exception)) - { - _logger.LogWarning(exception, "Settings integrity fingerprint could not be persisted."); - } - } - - private void ClearRecord(SecurityCredentialMetadata metadata) - { - if (metadata.SettingsIntegrity is null) - return; - - metadata.SettingsIntegrity = null; - try - { - _credentialStore.SaveMetadata(metadata); - } - catch (Exception exception) when (IsPersistenceFailure(exception)) - { - _logger.LogWarning(exception, "Settings integrity fingerprint could not be cleared."); - } - } - - private void OnConfigWritten(object? sender, EventArgs e) => AcceptCurrentFile(); - - private string? TryComputeDigest(out DateTimeOffset? lastWriteTimeUtc) - { - lastWriteTimeUtc = null; - try - { - var path = ConfigFilePath; - if (!File.Exists(path)) - return null; - - lastWriteTimeUtc = new DateTimeOffset(File.GetLastWriteTimeUtc(path), TimeSpan.Zero); - return Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(path))); - } - catch (Exception exception) when (IsPersistenceFailure(exception)) - { - _logger.LogWarning(exception, "Settings integrity fingerprint could not be computed."); - return null; - } - } - - private static bool IsPersistenceFailure(Exception exception) => - exception is IOException or UnauthorizedAccessException or CryptographicException; -} - -/// 设置文件与指纹记录不一致时用于启动提示的上下文。 -internal readonly record struct SettingsIntegrityMismatch( - DateTimeOffset RecordedAtUtc, - string? RecordedAppVersion, - DateTimeOffset? FileModifiedAtUtc); diff --git a/SecRandom/Services/Verification/DrawProofAttestationService.cs b/SecRandom/Services/Verification/DrawProofAttestationService.cs index 06764424c..ef46de1c0 100644 --- a/SecRandom/Services/Verification/DrawProofAttestationService.cs +++ b/SecRandom/Services/Verification/DrawProofAttestationService.cs @@ -53,7 +53,6 @@ public sealed class DrawProofAttestationService( private string? _queueFilePath; private bool _queueLoaded; private string? _lastError; - private int _chainAlertCount; /// /// Raised whenever the pending/attested state of a proof changes so the settings surface can refresh. @@ -113,7 +112,7 @@ public ProofAttestationStatus GetStatus() } } - return new ProofAttestationStatus(pending, failed, timestampFailed, conflict, _chainAlertCount, _lastError); + return new ProofAttestationStatus(pending, failed, timestampFailed, conflict, _lastError); } } @@ -249,7 +248,6 @@ private async Task ProcessItemAsync(ProofAttestationQueueItem item, Cancellation receipt = attestation.Receipt; // Kept in memory so a later timestamp failure does not ask the service to re-attest the same proof. item.Receipt = receipt; - RecordChainAnchor(proof, attestation.Chain); } if (requestedTimestamp) @@ -282,27 +280,6 @@ private async Task ProcessItemAsync(ProofAttestationQueueItem item, Cancellation } } - /// - /// Surfaces a chain position the service does not consider continuous with what it recorded before. - /// "behind" is the interesting one: the submitted chain is older than the anchor the service holds, - /// which is what a deleted-and-rebuilt local chain looks like from the outside. - /// - private void RecordChainAnchor(DrawProof proof, WitnessChainAnchor? anchor) - { - if (anchor is null || anchor.Status is not ("broken" or "gap" or "behind" or "conflict")) - return; - - lock (_gate) - { - _chainAlertCount++; - } - - logger.LogWarning( - "服务端证明链锚定报告异常。ProofId={ProofId},状态={Status},服务端链头={HeadIndex}", - proof.ProofId, anchor.Status, anchor.HeadIndex); - RaiseStatusChanged(); - } - /// /// Each stage gets its own budget: a slow attestation must not consume the time-stamp request's window. /// @@ -565,7 +542,6 @@ public sealed record ProofAttestationStatus( int FailedCount, int TimestampFailedCount, int ConflictCount, - int ChainAlertCount, string? LastError) { /// @@ -576,7 +552,7 @@ public sealed record ProofAttestationStatus( public bool HasOutstandingWork => PendingCount > 0 || FailedCount > 0; - public bool HasIssues => FailedCount > 0 || ConflictCount > 0 || ChainAlertCount > 0; + public bool HasIssues => FailedCount > 0 || ConflictCount > 0; } internal enum ProofSubmissionStage diff --git a/SecRandom/Services/Verification/DrawProofExportService.cs b/SecRandom/Services/Verification/DrawProofExportService.cs index 8b795b530..30d6107ed 100644 --- a/SecRandom/Services/Verification/DrawProofExportService.cs +++ b/SecRandom/Services/Verification/DrawProofExportService.cs @@ -15,7 +15,6 @@ namespace SecRandom.Services.Verification; public sealed class DrawProofExportService( MainConfigHandler configHandler, - ProofChainStore chainStore, ILogger logger) { private const int MaximumFileNameLength = 240; @@ -32,19 +31,18 @@ public sealed class DrawProofExportService( public DrawProofExportResult Save(DrawProof proof, DrawProofExportContext context) { RemoveExpiredProofs(configHandler.Data.General.ProofRetention.RetentionDays); - var chained = proof with { Chain = chainStore.NextChain(proof) }; - var timestamp = TimeZoneInfo.ConvertTime(chained.CreatedAtUtc, ChinaStandardTime); + var timestamp = TimeZoneInfo.ConvertTime(proof.CreatedAtUtc, ChinaStandardTime); var path = Utils.GetFilePath( "proofs", timestamp.ToString("yyyy-MM"), timestamp.ToString("yyyy-MM-dd"), - CreateFileName(chained, context)); - SaveAtPath(path, chained); + CreateFileName(proof, context)); + SaveAtPath(path, proof); RemoveProofsOverStorageLimit(configHandler.Data.General.ProofRetention.MaximumStorageBytes, path); logger.LogInformation( - "已导出抽取证明:ProofId={ProofId},模式={Mode},链序={ChainIndex},路径={Path}。", - chained.ProofId, chained.Mode, chained.Chain?.Index, path); - return new DrawProofExportResult(path, chained); + "已导出抽取证明:ProofId={ProofId},模式={Mode},路径={Path}。", + proof.ProofId, proof.Mode, path); + return new DrawProofExportResult(path, proof); } public void SaveAtPath(string path, DrawProof proof) @@ -117,17 +115,12 @@ private void RemoveExpiredProofs(int retentionDays) return; var cutoff = DateTime.UtcNow.AddDays(-retentionDays); - List removed = []; foreach (var path in Directory.EnumerateFiles(root, "*.srproof.json", SearchOption.AllDirectories)) { try { if (File.GetLastWriteTimeUtc(path) < cutoff) - { - if (TryReadChainIndex(path, out var chainIndex)) - removed.Add(chainIndex); File.Delete(path); - } } catch (IOException exception) { @@ -138,8 +131,6 @@ private void RemoveExpiredProofs(int retentionDays) logger.LogDebug(exception, "无权删除过期证明文件:{Path}。", path); } } - - chainStore.RecordRemovedIndices(removed, ProofChainEvent.RetentionCleanup); } private void RemoveProofsOverStorageLimit(long maximumStorageBytes, string protectedPath) @@ -157,23 +148,19 @@ private void RemoveProofsOverStorageLimit(long maximumStorageBytes, string prote .ThenBy(file => file.FullName, StringComparer.Ordinal) .ToList(); var totalBytes = files.Sum(file => file.Length); - List removed = []; foreach (var file in files) { if (totalBytes <= maximumStorageBytes) break; - // The proof saved by this very call must survive its own cleanup: deleting it would leave the - // chain head pointing at a file that never landed (a self-inflicted missing tail) and hand the - // attestation queue a path that no longer exists. + // The proof saved by this very call must survive its own cleanup: the attestation queue was + // handed this path and would otherwise be left pointing at a file that never landed. if (string.Equals(file.FullName, protectedPath, StringComparison.Ordinal)) continue; try { var length = file.Length; - if (TryReadChainIndex(file.FullName, out var chainIndex)) - removed.Add(chainIndex); file.Delete(); totalBytes -= length; } @@ -186,18 +173,6 @@ private void RemoveProofsOverStorageLimit(long maximumStorageBytes, string prote logger.LogDebug(exception, "无权删除超限证明文件:{Path}。", file.FullName); } } - - chainStore.RecordRemovedIndices(removed, ProofChainEvent.StorageLimitCleanup); - } - - private bool TryReadChainIndex(string path, out long chainIndex) - { - chainIndex = 0; - if (!TryRead(path, out var proof) || proof?.Chain is null) - return false; - - chainIndex = proof.Chain.Index; - return true; } private static TimeZoneInfo GetChinaStandardTime() diff --git a/SecRandom/Services/Verification/ProofChainStore.cs b/SecRandom/Services/Verification/ProofChainStore.cs deleted file mode 100644 index c09b671a3..000000000 --- a/SecRandom/Services/Verification/ProofChainStore.cs +++ /dev/null @@ -1,238 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Security.Cryptography; -using System.Text; -using System.Text.Json; -using System.Text.Json.Serialization; -using Microsoft.Extensions.Logging; -using SecRandom.Shared; -using SecRandom.Shared.Models.Verification; - -namespace SecRandom.Services.Verification; - -/// -/// Owns the append-only evidence chain over data/proofs. Each new proof records the previous -/// proof's chain hash, and the running head lives in data/proofs/chain-head.json. -/// Deleting proofs is recorded explicitly, because the app itself expires proofs by age and by storage -/// limit — an unrecorded deletion is what the chain is supposed to make visible. -/// -public sealed class ProofChainStore(ILogger logger) -{ - public const int CurrentFormatVersion = 1; - public const string HeadFileName = "chain-head.json"; - - private static readonly byte[] DomainSeparator = Encoding.ASCII.GetBytes("SecRandomProof/v3/chain"); - private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web) - { - WriteIndented = true, - Converters = { new JsonStringEnumConverter(JsonNamingPolicy.KebabCaseLower) } - }; - - private readonly object _gate = new(); - private ProofChainHeadDocument? _head; - private bool _headLoaded; - - public static string ComputeSelfHash(long index, string previousHash, string proofHash) - { - var previous = Encoding.ASCII.GetBytes(previousHash ?? string.Empty); - var current = Encoding.ASCII.GetBytes(proofHash ?? string.Empty); - var material = new byte[DomainSeparator.Length + sizeof(long) + previous.Length + current.Length]; - var offset = 0; - DomainSeparator.CopyTo(material, offset); - offset += DomainSeparator.Length; - BitConverter.TryWriteBytes(material.AsSpan(offset), index); - offset += sizeof(long); - previous.CopyTo(material, offset); - offset += previous.Length; - current.CopyTo(material, offset); - return WitnessClient.ToBase64Url(SHA256.HashData(material)); - } - - /// - /// Reserves the next chain position and advances the persisted head. The head is written before the - /// proof file, so a crash can leave at most one missing tail entry, which the verifier reports - /// separately from an interior gap. - /// - public DrawProofChain NextChain(DrawProof proof) - { - ArgumentNullException.ThrowIfNull(proof); - - lock (_gate) - { - var head = EnsureHeadLocked(); - var index = head.HeadIndex + 1; - var previousHash = head.HeadHash; - var proofHash = WitnessClient.ComputeAttestedProofHash(proof); - var selfHash = ComputeSelfHash(index, previousHash, proofHash); - head.HeadIndex = index; - head.HeadHash = selfHash; - PersistLocked(ProofChainEvent.ProofAppended); - return new DrawProofChain - { - FormatVersion = CurrentFormatVersion, - Index = index, - PrevHash = previousHash, - SelfHash = selfHash - }; - } - } - - /// - /// Records proofs the app itself removed (retention or storage-limit cleanup) so their absence is - /// explained instead of looking like tampering. Only a contiguous run starting right above the - /// current floor may advance : a sparse deletion such - /// as index 10 while 1-9 still exist must not turn those surviving gaps into "expired" files. - /// - public void RecordRemovedIndices(IEnumerable indices, ProofChainEvent reason) - { - ArgumentNullException.ThrowIfNull(indices); - - var removed = indices.Where(index => index > 0).ToArray(); - if (removed.Length == 0) - return; - - lock (_gate) - { - var head = EnsureHeadLocked(); - if (head.RemovedIndices is null) - head.RemovedIndices = []; - - var changed = false; - foreach (var index in removed) - { - if (index <= head.RetainedFromIndex || head.RemovedIndices.Contains(index)) - continue; - - head.RemovedIndices.Add(index); - changed = true; - } - - while (head.RemovedIndices.Remove(head.RetainedFromIndex + 1)) - { - head.RetainedFromIndex++; - changed = true; - } - - // Anything at or below the floor is already explained by the floor itself. - changed |= head.RemovedIndices.RemoveAll(index => index <= head.RetainedFromIndex) > 0; - if (!changed) - return; - - head.RemovedIndices.Sort(); - PersistLocked(reason); - } - } - - public ProofChainHead Read() - { - lock (_gate) - { - var head = EnsureHeadLocked(); - return new ProofChainHead( - head.FormatVersion, - head.HeadIndex, - head.HeadHash, - head.RetainedFromIndex, - head.LastEvent, - head.LastEventAtUtc); - } - } - - private ProofChainHeadDocument EnsureHeadLocked() - { - if (_headLoaded && _head is not null) - return _head; - - _headLoaded = true; - _head = new ProofChainHeadDocument(); - var path = TryResolveHeadPath(); - if (path is null || !File.Exists(path)) - return _head; - - try - { - var loaded = JsonSerializer.Deserialize(File.ReadAllText(path), JsonOptions); - if (loaded is not null) - _head = loaded; - } - catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or JsonException or NotSupportedException) - { - logger.LogWarning(exception, "证明链头读取失败,已从空链头继续。"); - } - - return _head; - } - - private void PersistLocked(ProofChainEvent reason) - { - var path = TryResolveHeadPath(); - if (path is null || _head is null) - return; - - try - { - _head.FormatVersion = CurrentFormatVersion; - _head.LastEvent = reason.ToString(); - _head.LastEventAtUtc = DateTimeOffset.UtcNow; - var temporaryPath = path + $".{Guid.NewGuid():N}.tmp"; - File.WriteAllText(temporaryPath, JsonSerializer.Serialize(_head, JsonOptions)); - File.Move(temporaryPath, path, true); - } - catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or JsonException or NotSupportedException) - { - logger.LogWarning(exception, "证明链头写入失败,证明文件仍会照常保存。"); - } - } - - private string? TryResolveHeadPath() - { - try - { - return Utils.GetFilePath("proofs", HeadFileName); - } - catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or NotSupportedException) - { - logger.LogDebug(exception, "无法解析证明链头路径。"); - return null; - } - } -} - -public enum ProofChainEvent -{ - ProofAppended, - RetentionCleanup, - StorageLimitCleanup, - Restore -} - -public sealed record ProofChainHead( - int FormatVersion, - long HeadIndex, - string HeadHash, - long RetainedFromIndex, - string? LastEvent, - DateTimeOffset LastEventAtUtc); - -internal sealed class ProofChainHeadDocument -{ - public int FormatVersion { get; set; } = ProofChainStore.CurrentFormatVersion; - - public long HeadIndex { get; set; } - - public string HeadHash { get; set; } = string.Empty; - - public long RetainedFromIndex { get; set; } - - /// - /// Removed indices above the floor that are not yet a contiguous prefix. They are what allows a later - /// deletion to close the hole and advance the floor without ever over-claiming. - /// - public List RemovedIndices { get; set; } = []; - - public string? LastEvent { get; set; } - - public DateTimeOffset LastEventAtUtc { get; set; } -} diff --git a/SecRandom/Services/Verification/ProofIntegrityVerifier.cs b/SecRandom/Services/Verification/ProofIntegrityVerifier.cs deleted file mode 100644 index 98b269910..000000000 --- a/SecRandom/Services/Verification/ProofIntegrityVerifier.cs +++ /dev/null @@ -1,198 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; - -namespace SecRandom.Services.Verification; - -/// -/// Rebuilds the local evidence chain from data/proofs and reports everything that cannot be -/// explained by the app's own retention cleanup. A local chain gives visibility, not protection: -/// an attacker who rewrites every file and the chain head can rebuild a self-consistent chain, so the -/// report must never be presented as proof that nothing was removed. -/// -public sealed class ProofIntegrityVerifier( - DrawProofExportService proofExporter, - ProofChainStore chainStore) -{ - private const int MaximumReportedIssues = 50; - - public ProofIntegrityReport Verify(CancellationToken cancellationToken = default) - { - var head = chainStore.Read(); - var issues = new List(); - var truncated = false; - var entries = new List(); - var unchained = 0; - var unreadable = 0; - - foreach (var path in proofExporter.EnumerateProofPaths()) - { - cancellationToken.ThrowIfCancellationRequested(); - if (!proofExporter.TryRead(path, out var proof) || proof is null) - { - unreadable++; - AddIssue(issues, ref truncated, ProofIntegrityIssueKind.Unreadable, path, "证明文件无法解析"); - continue; - } - - if (proof.Chain is null) - { - unchained++; - continue; - } - - if (proof.Chain.FormatVersion != ProofChainStore.CurrentFormatVersion) - { - AddIssue(issues, ref truncated, ProofIntegrityIssueKind.UnsupportedVersion, path, - $"不支持的链格式版本 {proof.Chain.FormatVersion}"); - continue; - } - - var expectedSelfHash = ProofChainStore.ComputeSelfHash( - proof.Chain.Index, - proof.Chain.PrevHash, - WitnessClient.ComputeAttestedProofHash(proof)); - if (!string.Equals(expectedSelfHash, proof.Chain.SelfHash, StringComparison.Ordinal)) - { - AddIssue(issues, ref truncated, ProofIntegrityIssueKind.Modified, path, "文件内容与链上记录不一致"); - continue; - } - - entries.Add(new ChainedProof(path, proof.Chain.Index, proof.Chain.PrevHash, proof.Chain.SelfHash)); - } - - entries.Sort((left, right) => left.Index.CompareTo(right.Index)); - var gaps = 0; - var expired = 0; - var brokenLinks = 0; - var beyondHead = 0; - - // Indices below the first surviving proof are missing too; only the recorded retention floor explains them. - if (entries.Count > 0) - { - var expectedFirst = head.RetainedFromIndex + 1; - if (entries[0].Index > expectedFirst) - { - gaps++; - AddIssue(issues, ref truncated, ProofIntegrityIssueKind.Gap, entries[0].Path, - $"链序 {expectedFirst}-{entries[0].Index - 1} 缺少证明文件"); - } - } - - for (var index = 0; index < entries.Count; index++) - { - var entry = entries[index]; - if (entry.Index > head.HeadIndex) - { - beyondHead++; - AddIssue(issues, ref truncated, ProofIntegrityIssueKind.BeyondHead, entry.Path, - $"链序 {entry.Index} 超过链头 {head.HeadIndex}"); - } - - if (index == 0) - continue; - - var previous = entries[index - 1]; - if (!string.Equals(entry.PrevHash, previous.SelfHash, StringComparison.Ordinal)) - { - brokenLinks++; - AddIssue(issues, ref truncated, ProofIntegrityIssueKind.BrokenLink, entry.Path, - $"链序 {entry.Index} 的前一链哈希与链序 {previous.Index} 不衔接"); - } - - if (entry.Index == previous.Index + 1) - continue; - - var missingFrom = previous.Index + 1; - var missingTo = entry.Index - 1; - if (missingTo <= head.RetainedFromIndex) - { - expired++; - continue; - } - - gaps++; - AddIssue(issues, ref truncated, ProofIntegrityIssueKind.Gap, entry.Path, - $"链序 {missingFrom}-{missingTo} 缺少证明文件"); - } - - var highestChained = entries.Count == 0 ? head.RetainedFromIndex : entries[^1].Index; - var missingTail = (int)Math.Max(0, Math.Min(head.HeadIndex - highestChained, int.MaxValue)); - if (missingTail > 0) - { - AddIssue(issues, ref truncated, ProofIntegrityIssueKind.MissingTail, string.Empty, - $"链序 {highestChained + 1}-{head.HeadIndex} 未落盘"); - } - - return new ProofIntegrityReport( - entries.Count + unchained + unreadable, - entries.Count, - unchained, - unreadable, - expired, - gaps, - brokenLinks, - issues.Count(issue => issue.Kind == ProofIntegrityIssueKind.Modified), - beyondHead, - missingTail, - head.HeadIndex, - head.RetainedFromIndex, - truncated, - issues); - } - - private static void AddIssue( - List issues, - ref bool truncated, - ProofIntegrityIssueKind kind, - string path, - string detail) - { - if (issues.Count >= MaximumReportedIssues) - { - truncated = true; - return; - } - - issues.Add(new ProofIntegrityIssue(kind, path, detail)); - } - - private sealed record ChainedProof(string Path, long Index, string PrevHash, string SelfHash); -} - -public enum ProofIntegrityIssueKind -{ - Unreadable, - Modified, - UnsupportedVersion, - BrokenLink, - Gap, - BeyondHead, - MissingTail -} - -public sealed record ProofIntegrityIssue(ProofIntegrityIssueKind Kind, string Path, string Detail); - -public sealed record ProofIntegrityReport( - int Total, - int Chained, - int Unchained, - int Unreadable, - int Expired, - int Gaps, - int BrokenLinks, - int Modified, - int BeyondHead, - int MissingTail, - long HeadIndex, - long RetainedFromIndex, - bool IssuesTruncated, - IReadOnlyList Issues) -{ - /// - /// Missing-tail entries are expected after a crash between the chain-head write and the proof write, - /// so they are reported but do not mark the chain unhealthy. Everything else is unexplained. - /// - public bool IsHealthy => Gaps == 0 && BrokenLinks == 0 && Modified == 0 && BeyondHead == 0; -} diff --git a/SecRandom/Services/Verification/VerificationDrawCoordinator.cs b/SecRandom/Services/Verification/VerificationDrawCoordinator.cs index ab73beffa..3718f5661 100644 --- a/SecRandom/Services/Verification/VerificationDrawCoordinator.cs +++ b/SecRandom/Services/Verification/VerificationDrawCoordinator.cs @@ -24,7 +24,6 @@ public sealed class VerificationDrawCoordinator( IVerificationKernel kernel, DrawProofExportService proofExporter, DrawProofAttestationService attestationService, - ProofChainStore chainStore, IProfileService profileService, MainConfigHandler configHandler, IWitnessClient witnessClient, @@ -184,7 +183,6 @@ private async Task> DrawAsync( VerificationKernelResult result; if (verificationMode == VerificationMode.FormalNotarized) { - var head = chainStore.Read(); var request = new FormalNotarizationRequest { ProofId = Guid.NewGuid(), @@ -192,9 +190,7 @@ private async Task> DrawAsync( InputHash = WitnessClient.ToBase64Url(inputHash), ZeroSeedRequest = WitnessClient.ToBase64Url(VerificationWireCodec.EncodeDrawRequest(input, new byte[32])), AuditPayload = WitnessClient.ToBase64Url(input.AuditPayload), - ClientNonce = WitnessClient.ToBase64Url(VerificationSeedDerivation.CreateCsprngNonce()), - ChainIndex = head.HeadIndex, - ChainHash = head.HeadHash + ClientNonce = WitnessClient.ToBase64Url(VerificationSeedDerivation.CreateCsprngNonce()) }; proof = await witnessClient.NotarizeAsync(request, cancellationToken).ConfigureAwait(false); result = VerificationWireCodec.DecodeDrawResponse(GetResponse(proof)); diff --git a/SecRandom/Services/Verification/WitnessClient.cs b/SecRandom/Services/Verification/WitnessClient.cs index 2d969abad..067c3b170 100644 --- a/SecRandom/Services/Verification/WitnessClient.cs +++ b/SecRandom/Services/Verification/WitnessClient.cs @@ -52,7 +52,7 @@ public async Task AttestAsync( receipt.Mode != proof.Mode) throw new InvalidDataException("Server attestation is not bound to this proof."); - return new WitnessAttestationResult(envelope.Token, envelope.Chain); + return new WitnessAttestationResult(envelope.Token); } public async Task NotarizeAsync( diff --git a/SecRandom/Services/Verification/WitnessContracts.cs b/SecRandom/Services/Verification/WitnessContracts.cs index 5cf807454..cb382c6bf 100644 --- a/SecRandom/Services/Verification/WitnessContracts.cs +++ b/SecRandom/Services/Verification/WitnessContracts.cs @@ -1,4 +1,5 @@ using System; +using System.Text.Json.Serialization; using System.Threading; using System.Threading.Tasks; using SecRandom.Shared.Models.Verification; @@ -22,25 +23,9 @@ public sealed class WitnessAttestationResponse { public string Token { get; init; } = string.Empty; public string KeyId { get; init; } = string.Empty; - - // Present only when the service anchors local proof chains; older deployments omit it. - public WitnessChainAnchor? Chain { get; init; } } -/// -/// How the service compared this submission's chain position with what it previously recorded for the -/// same client. behind means the submitted chain is older than the anchor the service already -/// holds, which is what a deleted-and-rebuilt local chain looks like from the outside. -/// -public sealed class WitnessChainAnchor -{ - public string Status { get; init; } = string.Empty; - public long? HeadIndex { get; init; } - public string? HeadHash { get; init; } - public int Breaks { get; init; } -} - -public sealed record WitnessAttestationResult(string Receipt, WitnessChainAnchor? Chain); +public sealed record WitnessAttestationResult(string Receipt); public sealed class FormalNotarizationRequest { @@ -51,9 +36,12 @@ public sealed class FormalNotarizationRequest public string AuditPayload { get; init; } = string.Empty; public string ClientNonce { get; init; } = string.Empty; - // The local chain head held before this notarization. The service only records it so the chain anchor - // covers formal draws as well; it never takes part in the locked-input comparison. - public long ChainIndex { get; init; } + // Legacy chain position fields kept on the wire contract only: this build keeps no local proof chain, + // so they stay null and are omitted from the request. The service never used them for locking. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public long? ChainIndex { get; init; } + + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public string? ChainHash { get; init; } } diff --git a/SecRandom/Views/SettingsPages/AGENTS.md b/SecRandom/Views/SettingsPages/AGENTS.md index abb13c97a..638a96ae8 100644 --- a/SecRandom/Views/SettingsPages/AGENTS.md +++ b/SecRandom/Views/SettingsPages/AGENTS.md @@ -15,13 +15,13 @@ Settings navigation subtree: top-level settings pages, grouped settings pages, a SecRandom/Views/SettingsPages/ |-- HomeSettingsPage.axaml(.cs) # Top-level student-history overview |-- DebugSettingsPage.axaml(.cs) # Runtime-hidden bottom debug page -|-- General/ # settings.general.*: basic/security/backup/privacy/control +|-- General/ # settings.general.*: basic/security/backup/storage/privacy/control |-- ListManagement/ # settings.listManagement.*: roll-call/lottery list entries |-- Personalized/ # settings.personalized.*: appearance/floatingWindow/timer/music library |-- Picking/ # settings.picking.*: draw settings + face detector -|-- Notification/ # settings.notification.*: voice and per-draw notification channels +|-- Notification/ # settings.notification.*: voice, built-in notification floating window, and per-draw notification channels |-- History/ # settings.history.*: management + roll-call/lottery history pages -|-- About/ # settings.about: about page with external links +|-- About/ # settings.about: about page with external links, this-device info, and draw-mode versions |-- Linkage/ # settings.linkage: linkage settings |-- More/ # settings.more: more settings |-- Plugins/ # settings.plugin: local SRPX plugin management @@ -38,8 +38,9 @@ SecRandom/Views/SettingsPages/ | General settings behavior | `General/BasicSettingsPage.axaml(.cs)` | Language change triggers `SettingsView.Current?.RequestRestartApp()`. | | Privacy settings behavior | `General/PrivacySettingsPage.axaml(.cs)` | Binds to `MainConfigModel.General.PrivacySettings`; Sentry telemetry changes apply live through `TelemetryRuntimeService`, and online status changes apply live through `OnlineStatusService`. | | Control settings behavior | `General/ControlSettingsPage.axaml(.cs)` + `ViewModels/SettingsPages/ControlSettingsPageViewModel.cs` | Page ID `settings.general.control` (desktop/tablet). It is the only 集控 surface, and its card order is fixed: 远程控制 (`S_RemoteControl`) → 集控平台 (`S_ControlPlatform`) → 节点信息 (`S_NodeInfo`) → 连接与状态 (`S_ConnectionStatus`) → 高级连接设置 (`S_AdvancedConnections`) last, i.e. 允许被远程控制 switch → 集控平台 row → 显示名称(`DisplayName`,留空则上报主机名 `ControlNodeClientOptions.HostName`,输入框以它作水印)→ node ID → 所属组 ID → 接入自建集控(`S_NodeEnrollment`)→ 连接状态(含 立即重连)→ 抽取锁定 → the 高级连接设置 group (节点通道地址 + 控制面地址). **显示名称 / node ID / 所属组 ID 这三行永远可见**,任何开关都不隐藏它们;最后那组地址卡同样**永远可见**——调试页那个 `IControlPlaneEndpointSettingsGate` 总开关已连同它的设置卡一起删除,两条地址都不再有显隐开关。Both address rows are laid out identically — a fixed-width textbox plus the same `C_RestoreDefaultEndpoint` 恢复默认 button (`ResetServerUrlCommand` / `ResetControlPlaneEndpointCommand`, each enabled only while that address actually differs from its default) — so the two rows keep the same total width; the 控制面地址 textbox additionally treats empty as "back to the online default". The 接入自建集控 card (`S_NodeEnrollment`, between 所属组 ID and 连接状态) is **not an expander at all**: it deliberately declares **no items** and puts everything (the status/code/button row *and* the failure text) inside a single `fa:FASettingsExpander.Footer`, because FluentAvalonia renders the expand/collapse chevron the moment the card has one item and then reserves a collapsible body area — an item-free card has no chevron and no body, so it reads as a plain settings card. The failure text is the Footer's second row (`IsVisible="{Binding ShowEnrollmentMessage}"`), so nothing there can ever be folded away. Its 状态 line is right-aligned against the code box, the 接入码 textbox carries `MaxLength="{Binding EnrollmentCodeMaxLength}"` (`NodeEnrollmentClient.MaxCodeLength`, deliberately generous because the user may paste a whole `srn_…` token — it is a UI guard against pasting a document, not a protocol limit), and 接入 / 清除接入 share **one** action slot through complementary visibility (`ShowEnroll => !ShowClearEnrollment`, `ShowClearEnrollment => CanClearEnrollment && an empty code box`), so exactly one button occupies that slot at all times and the row width never jumps, while each button keeps its own `CanEnroll` / `CanClearEnrollment` for the enabled state. The 集控平台 row stays visible for everyone: its button opens the effective base URL through `IExternalLauncher.TryOpenUri`(按钮文案随 `IControlPlaneEndpointStore.IsCustom` 在"打开SecRandom集控平台"/"打开第三方托管集控平台"之间切换,绝不让按钮写着官方却跳到第三方). It never touches `settings.json` — the switch, identity, endpoint, applied `desired_state` revision, and draw lock live in `data/config/control/node-state.json` through `IControlNodeStateStore`, because a settings import must not be able to enable remote control; an invalid endpoint is reported instead of persisted (`ControlEndpointPolicy`). The control-plane base URL is the same story with a different threat: it receives this account's bearer token on every request, so it lives in `data/config/control-plane/endpoint.json` (`IControlPlaneEndpointStore`, validated by `ControlPlaneEndpointPolicy`: https, or plaintext only to loopback) rather than an importable settings file. Because this ViewModel holds runtime state rather than a `ConfigHandler` sub-model, the page sets `DataContext` to that ViewModel (registered as a `ControlSettingsPageViewModel` singleton inside the desktop control-node block of `BuildHost`, because its `Changed`/`LinkStateChanged` subscriptions would otherwise accumulate on every page open) and refreshes from `IControlNodeStateStore.Changed` + `ControlNodeClient.LinkStateChanged` through the UI dispatcher. | -| Backup settings UI | `General/BackupSettingsPage.axaml(.cs)` | The page is one `TabStrip` + `Carousel` pair. The 本地备份 tab lists real backup ZIPs under app data and delegates create/restore to `IImportExportService`, which validates archives and creates the required pre-restore snapshot. The 云端备份 tab (desktop and mobile) owns account state, cloud quota (auto-fetched on page entry, after sign-in, and after an automatic backup, with its own refresh command and 正在获取 loading label), an 打开 思拓创联 云储存页面 row that opens `https://sectl.cn/dashboard/cloud` through `IExternalLauncher.TryOpenUri`, 立即备份到云端 with a transient 上传中ing~ status plus cancel instead of a part-progress card, its own 云端备份内容 rows (`CloudInclude*`; no log or theme row because logs, the device identity, the voice cache, and theme resources can never be uploaded, while 抽取证明文件 has a row backed by `BackupConfig.CloudIncludeProofs` that defaults to off because a cloud copy is the last resort once the local chain has been deleted), a 设备别名 row (`BackupConfig.CloudDeviceAlias`, persisted through the page's existing `Settings.PropertyChanged` save boundary and shown in the cloud file names; empty means the host name), no 云端备份加密 row (client-side encryption and its passphrase were removed, so the archive is uploaded with account access as its only key), and 云端备份管理 columns (file name, 上传时间, size, actions) where a package the removed feature uploaded is flagged 旧版加密,无法恢复 in the file-name cell because `CanRestore` is false for it), with 云端自动备份 rows (switch/interval/limit persisted as `BackupConfig.CloudAutoBackup*`, independent of the local auto backup; the limit is per device, while an exhausted quota still deletes the account-wide oldest backup), and cloud backup management (download-restore/delete/cleanup) behind a separator with a left-aligned 刷新中ing~/清理中ing~ status label; an upload refreshes the cloud list whether it succeeds or fails. The cloud tab item carries the `S_CloudBackup` search anchor. The page resolves `SectlAuthService`/`CloudBackupService` with `TryGetService`, hides the entire cloud tab when either is missing (mobile), delegates all cloud work to `CloudBackupService`, and must not cache cloud state in configuration. | -| Security settings | `General/SecuritySettingsPage.axaml(.cs)` | Page ID `settings.general.security`; belongs to the General navigation group. Its Sudo card is one expandable `FASettingsExpander` (`x:Name="S_SudoMode"`) holding the Sudo switch (`S_SudoMode_Enabled`, tag `SudoModeEnabled`), the duration row (`S_SudoMode_Duration`), and three explanation lines that spell out the operation scope, the settings-window scope, and the operations Sudo never covers; the duration control is disabled while Sudo is off and both rows write through `UpdateSecuritySettingsAsync`. Its 防篡改 section holds the settings-file integrity switch, the 篡改处理方式 picker (`SettingsIntegrityAction`: password confirmation or automatic restore), and the restore-source picker (`SettingsIntegrityRestoreSource`, shown only while automatic restore is selected); both pickers are plain `SettingOption` ComboBoxes persisted through the security-gated update boundary. The credential section keeps its password commands and pairs the TOTP command button (`C_SetTotp`/`C_ResetTotp`) with a `C_RemoveTotp` button that is visible only while TOTP is configured; removal calls `ISecurityService.RemoveTotpAsync` (fresh password, deletes the seed and the standalone copy) instead of clearing the factor switch. Cloud candidates stay restricted to this device's own uploads (`CloudBackupService.IsOwnBackup`), so another machine's cloud backup is never used to restore this machine's settings file. The page binds its model to `SecuritySettingsStore.Data` (not `ViewModel.Config`): these switches live in the encrypted `data/config/security/settings.json`, so the store — not the main config handler — is what persists them. | +| Backup settings UI | `General/BackupSettingsPage.axaml(.cs)` | The page edits local backups only. It lists real backup ZIPs under app data and delegates create/restore/delete to `IImportExportService`, which validates archives and creates the required pre-restore snapshot; the backup-content multi-select persists through the page's `Settings.PropertyChanged` save boundary. The former cloud backup tab (account state, quota, device alias, `CloudInclude*` selection, cloud list/restore/delete/cleanup) was removed together with the account cloud backup feature, so the page no longer resolves `SectlAuthService`/`CloudBackupService` and owns no `Cloud*` state. | +| Storage settings | `General/StorageSettingsPage.axaml(.cs)` | Page ID `settings.general.storage` (General group, desktop only, right after Backup); the only surface that chooses the desktop data directory. It shows the resolved root, mode, source and anchor path, offers the three modes (package data / per-user standard root / custom folder), lists other detected data locations without migrating them automatically, and its migrate button validates the target through `DataRootMigrationEngine.Validate`, writes `data-root-journal.json`, authorizes as `SecurityOperation.RestartApplication`, then restarts with `--data-root-migration `. The copy/verify/commit work belongs to the restart-time `DataRootMigrationWindow`; the page must never copy files or write the anchor itself, because the engine's anchor write is the single commit point. | +| Security settings | `General/SecuritySettingsPage.axaml(.cs)` | Page ID `settings.general.security`; belongs to the General navigation group. Its Sudo card is one expandable `FASettingsExpander` (`x:Name="S_SudoMode"`) holding the Sudo switch (`S_SudoMode_Enabled`, tag `SudoModeEnabled`), the duration row (`S_SudoMode_Duration`), and three explanation lines that spell out the operation scope, the settings-window scope, and the operations Sudo never covers; the duration control is disabled while Sudo is off and both rows write through `UpdateSecuritySettingsAsync`. The credential section keeps its password commands and pairs the TOTP command button (`C_SetTotp`/`C_ResetTotp`) with a `C_RemoveTotp` button that is visible only while TOTP is configured; removal calls `ISecurityService.RemoveTotpAsync` (fresh password, deletes the seed and the standalone copy) instead of clearing the factor switch. The page binds its model to `SecuritySettingsStore.Data` (not `ViewModel.Config`): these switches live in the encrypted `data/config/security/settings.json`, so the store — not the main config handler — is what persists them. | | Managed draw music | `SecRandom/Services/Music/`, `SecRandom/Services/Draw/DrawAudioService.cs` | Library files live under `data/audio/music`; app-layer service resolves selections and owns cross-platform playback. | | Course linkage | `SecRandom/Services/Linkage/` | CSES schedule storage/parsing, ClassIsland IPC adapter, course-boundary runtime, draw authorization, and pre-class reset. Break/after-class drawing is decided only here: `CourseLinkageService.IsConfirmedNonClassTime` (setting on + confirmed `CourseTimeState.Breaking` + outside the pre-class enable / post-class delay windows), while an unavailable snapshot (`IsAvailable == false`) always stays permissive; `LinkageDrawCoordinator.AuthorizeAsync` is the single gate for roll-call, quick draw, lottery, protocol and shortcut paths, and its hard-block branch (`VerificationRequired == false`) fires `ClassTimeDrawRestrictionNotice` so the button never dies silently. ClassIsland connect/disconnect flows through the same snapshot, so a broken IPC link degrades to "no restriction" instead of a permanent lock. | | List management settings | `ListManagement/RollCallListSettingsPage.axaml(.cs)`, `ListManagement/LotteryListSettingsPage.axaml(.cs)`, `ListManagement/RosterImportRegionSelector.axaml(.cs)` | Point-call list and lottery prize-pool viewing/import. Spreadsheet imports let the user pick the import range (worksheet, header row, data row range) through the shared `RosterImportRegionSelector`, which shows a clickable raw row preview and hands the region back through `RegionChanged`; the drawers keep the raw grid, rebuild column mapping on every region change, and re-read the file by name on `SheetSelectionChanged`. Adding a single member or prize checks the typed number against the list through `SecRandom.Core/Services/Profiles/ProfileSequenceNumbering.cs`: one colliding plain number offers 顺延并插入 (insert at that position and shift every numeric number at or above it by one), 追加到末尾 (take max + 1), or 返回修改 (reopen the form with the draft); a non-numeric or already duplicated number offers only 保留重复并添加 / 返回修改, because shifting could not make the number unique. Renumbering rewrites only the visible `Id`/number, never `RecordId`, so draw history, temporary records, and fairness weights stay attached to the member. | @@ -54,9 +55,10 @@ SecRandom/Views/SettingsPages/ | Update settings | `Update/UpdateSettingsPage.axaml(.cs)` | Shared `settings.update` bottom-nav entry for desktop and mobile. | | Account access | `../../Services/Auth/SectlAuthService.cs`, `../SettingsView.axaml(.cs)` | Desktop settings title bar shows the signed-in account and keeps OAuth PKCE sign-in/sign-out in the account flyout. | | Notification settings | `Notification/VoiceSettingsPage.axaml(.cs)` etc. | Voice/music and notification channel entries under `settings.notification`. | +| Built-in notification floating window | `Notification/NotificationFloatingWindowSettingsPage.axaml(.cs)` | Page ID `settings.notification.floatingWindow`, registered right after the lottery channel page and immediately before `settings.notification.fullscreen`, so it sits directly above 全屏通知 in the sidebar. It is the only editor of the built-in notification floating window's geometry — position, monitor, horizontal/vertical offset, and opacity — and binds the global `NotificationSettings.Default` channel directly rather than a per-channel override. Channel pages therefore carry no 通知窗口 card: `OverridableNotificationChannelSettings.OverrideNotificationWindowSettings` is a legacy field that `FloatingWindowSettingsUnifiedInitialized` folds back to `false` when the settings file is loaded, and `GetOverrideNotificationSettings(..., NotificationWindow)` still resolves to `Default` while it is false. English title `Page_FloatingWindow` is "Built-in Notification Floating Window"; the description copy makes clear this is the small floating window, not the fullscreen one. | | History management | `History/HistoryManagementSettingsPage.axaml(.cs)` | Clears roll-call/lottery histories through active-profile or named-profile handlers, and exports them: each section pairs a multi-select scope (`sr:MultiComboBox`, all selected by default) with course, time-range, time-order and file-format rows plus a 导出 button, then uses `StorageProvider.SaveFilePickerAsync` whose file type follows the selection (one profile → `.xlsx`/`.csv`, several → `.zip`) and delegates all generation to Core `IHistoryExportService`; a workbook carries the record sheet, the summary sheet, then one extra sheet per member that has records. Every export covers all members of the selected lists — there is deliberately no per-person row; the course row appears only when the selection carries course values. The mobile path writes a temporary file and copies it into `OpenWriteAsync` when `TryGetLocalPath()` is null; `settings.history.management`. | | Log viewer | `LogViewer/LogViewerSettingsPage.axaml(.cs)` | Hidden page `settings.logs`; opened from the settings shell more-options menu. | -| About / external links | `About/AboutSettingsPage.axaml(.cs)` | `settings.about` bottom-nav; `Process.Start` for external URLs. | +| About / external links | `About/AboutSettingsPage.axaml(.cs)` | `settings.about` bottom-nav; `Process.Start` for external URLs. Two read-only diagnostic cards sit between the app card and 作者: `S_Machine` 本机信息 (computer name, `RuntimeInformation` OS/architecture/runtime, logical processor count, `GlobalConstants.VersionLong`, `Utils.PackageRoot`, `Utils.DataRoot`, all resolved once in code-behind with a 复制本机信息 footer button that writes `Label: value` lines to the clipboard) and `S_DrawModes` 抽取模式 (the four built-in modes `builtin.random`/`fair`/`inventory`/`weighted` with their localized names and descriptions; each row's footer shows `S_DrawModes_Version` = `GlobalConstants.Version`, because no per-mode version exists — built-in algorithms ship with the app build — and the card footer shows `S_DrawModes_Engine` = `VerificationWireCodec.AlgorithmEngineVersion`, the proof-replay generation). Plugin-registered modes are deliberately absent: their registration carries no version. | | Shell navigation semantics | `../SettingsView.axaml.cs` | Default page `settings.overview`, history stack, generated menu. | | Localization pairing | `../../Langs/SettingsPages/` | Page folders mirror settings-page domains, including the runtime-hidden Debug page. | @@ -77,7 +79,7 @@ SecRandom/Views/SettingsPages/ - Searchable setting rows must use a stable `x:Name` matching their active `S_` localization ID; nested rows may use the visual-tree fallback, while stale localization entries should not be exposed as searchable targets. - V2-parity settings pages should keep the same `ScrollViewer` + `StackPanel.page-container animated-intro` + `FASettingsExpander` rhythm as existing settings pages. - A page containing multiple settings categories should use `IconText` category headings followed by sibling `FASettingsExpander` rows. Override groups follow the committed draw-settings pattern: one outer `FASettingsExpander` whose direct rows are `FASettingsExpanderItem` controls; never nest another `FASettingsExpander` inside it. -- Default notification settings follow the default draw-settings layout: category `IconText` headings with sibling non-grouping `FASettingsExpander` rows. Only per-draw notification pages use collapsible override groups. +- Default notification settings follow the default draw-settings layout: category `IconText` headings with sibling non-grouping `FASettingsExpander` rows. Only per-draw notification pages use collapsible override groups. The built-in floating window's geometry (position, monitor, offset, opacity) is global — edited only on `NotificationFloatingWindowSettingsPage` against `NotificationSettings.Default` — so the shared channel content must not grow a 通知窗口 row again; the per-channel override toggle that used to sit there was removed together with its card. - Linkage settings owns only the CSES picker, import/summary/clear commands, and config bindings. It must delegate schedule validation and file replacement to `ICsesScheduleStore`; ClassIsland state, timing, and draw enforcement belong to the linkage services. - Voice/music owns the global TTS engine, voice, volume, and content switches. Per-student/per-prize specific announcement controls belong in list management attached settings for both roll-call and lottery records. - The voice page registers OmniTTS (engine 2) on every non-iOS platform (`!OperatingSystem.IsIOS()` stays). Its OmniTTS-only rows (provider, API base URL, API key, model, voice, instructions, MiMo design description/clone reference, batch cache, clear cache) live in one section bound to `IsOmniTtsSelected` and appear only while `VoiceEngine == 2`; model and voice rows are editable ComboBoxes so the user can always type values, with a fetch button pulling the model list from the provider API. MiMo clone imports require explicit authorization and WAV input; the reference is private under `data/config/voice/` and is never serialized into settings. API keys never enter the settings model — they go through `OmniTtsCredentialStore` (`data/config/voice/omnitts-keys.json`). diff --git a/SecRandom/Views/SettingsPages/General/BackupSettingsPage.axaml b/SecRandom/Views/SettingsPages/General/BackupSettingsPage.axaml index 713d0ed7c..d44671ffc 100644 --- a/SecRandom/Views/SettingsPages/General/BackupSettingsPage.axaml +++ b/SecRandom/Views/SettingsPages/General/BackupSettingsPage.axaml @@ -5,335 +5,132 @@ xmlns:sr="http://secrandom.sectl.cn/schemas/xaml/core" xmlns:fa="clr-namespace:FluentAvalonia.UI.Controls;assembly=FluentAvalonia" xmlns:local="clr-namespace:SecRandom.Views.SettingsPages.General" - xmlns:lc="clr-namespace:SecRandom.Langs.Common" xmlns:lsb="clr-namespace:SecRandom.Langs.SettingsPages.General.Backup" mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450" - x:Class="SecRandom.Views.SettingsPages.General.BackupSettingsPage" - Loaded="OnLoaded" - Unloaded="OnUnloaded" + x:Class="SecRandom.Views.SettingsPages.General.BackupSettingsPage" + Loaded="OnLoaded" + Unloaded="OnUnloaded" x:DataType="local:BackupSettingsPage"> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/SecRandom/Views/SettingsPages/General/BackupSettingsPage.axaml.cs b/SecRandom/Views/SettingsPages/General/BackupSettingsPage.axaml.cs index a3c16fe28..960d58c2b 100644 --- a/SecRandom/Views/SettingsPages/General/BackupSettingsPage.axaml.cs +++ b/SecRandom/Views/SettingsPages/General/BackupSettingsPage.axaml.cs @@ -7,12 +7,10 @@ using System.IO; using System.Linq; using System.Runtime.CompilerServices; -using System.Threading; using System.Threading.Tasks; using Avalonia.Collections; using Avalonia.Controls; using Avalonia.Interactivity; -using Avalonia.Threading; using FluentAvalonia.UI.Controls; using Microsoft.Extensions.Logging; using SecRandom.Core.Abstraction; @@ -21,9 +19,7 @@ using SecRandom.Core.Icons; using SecRandom.Core.Models.SubConfigs.General; using SecRandom.Models; -using SecRandom.Services.Auth; using SecRandom.Services.Desktop; -using SecRandom.Core.Services.Archive; using SecRandom.Services.ImportExport; using SecRandom.Shared; using SecRandom.ViewModels; @@ -36,29 +32,13 @@ public partial class BackupSettingsPage : UserControl, INotifyPropertyChanged { private const string BackupDirectoryName = "backup"; - /// SECTL personal cloud storage dashboard, opened in the system browser. - private const string CloudStoragePageUrl = "https://sectl.cn/dashboard/cloud"; - private string _backupUsageText = FormatSize(0); private bool _isSubscribed; private bool _isIncludeOptionsSubscribed; - private bool _isCloudBusy; - private bool _isCloudUploading; - private bool _isCloudRefreshing; - private bool _isCloudQuotaRefreshing; - private bool _isAccountSubscribed; - private bool _isCloudEventSubscribed; - private string _cloudAccountText = string.Empty; - private string _cloudQuotaText = string.Empty; - private string _cloudListStatusText = string.Empty; - private CancellationTokenSource? _cloudOperation; - private readonly Dictionary _cloudDescriptors = new(StringComparer.Ordinal); private event PropertyChangedEventHandler? NotifyPropertyChanged; private readonly ILogger _logger = IAppHost.GetService>(); private readonly IImportExportService _importExportService = IAppHost.GetService(); - private readonly SectlAuthService? _authService = IAppHost.TryGetService(); - private readonly CloudBackupService? _cloudBackupService = IAppHost.TryGetService(); private IExternalLauncher ExternalLauncher { get; } = IAppHost.GetService(); public BackupSettingsPage() @@ -84,24 +64,6 @@ public BackupSettingsPage() value => Settings.IncludeLogs = value) ]; SelectedIncludeOptions = BuildSelectedOptions(IncludeOptions); - CloudIncludeOptions = - [ - new(LR.S_Includes_Config, () => Settings.CloudIncludeConfig, - value => Settings.CloudIncludeConfig = value), - new(LR.S_Includes_List, () => Settings.CloudIncludeList, - value => Settings.CloudIncludeList = value), - new(LR.S_Includes_History, () => Settings.CloudIncludeHistory, - value => Settings.CloudIncludeHistory = value), - new(LR.S_Includes_Audio, () => Settings.CloudIncludeAudio, - value => Settings.CloudIncludeAudio = value), - new(LR.S_Includes_Cses, () => Settings.CloudIncludeCses, - value => Settings.CloudIncludeCses = value), - new(LR.S_Includes_Images, () => Settings.CloudIncludeImages, - value => Settings.CloudIncludeImages = value), - new(LR.S_Includes_Proofs, () => Settings.CloudIncludeProofs, - value => Settings.CloudIncludeProofs = value) - ]; - SelectedCloudIncludeOptions = BuildSelectedOptions(CloudIncludeOptions); DataContext = this; InitializeComponent(); SubscribeSettings(); @@ -112,112 +74,9 @@ public BackupSettingsPage() public BackupConfig Settings { get; } public ObservableCollection Backups { get; } = []; - public ObservableCollection CloudBackups { get; } = []; public AvaloniaList IncludeOptions { get; } public AvaloniaList SelectedIncludeOptions { get; } - /// - /// Cloud backup content is its own selection; the cloud list has no log row because logs, - /// the device identity, and the voice cache can never be uploaded. - /// - public AvaloniaList CloudIncludeOptions { get; } - public AvaloniaList SelectedCloudIncludeOptions { get; } - - /// - /// The cloud section only exists where the desktop SECTL account services are registered; the - /// mobile host has no account session, so it hides the whole section instead of failing. - /// - public bool IsCloudVisible => _cloudBackupService is not null && _authService is not null; - - public bool IsCloudSignedIn => _authService?.IsSignedIn == true; - - public bool IsCloudBusy - { - get => _isCloudBusy; - private set - { - if (_isCloudBusy == value) - return; - - _isCloudBusy = value; - OnPropertyChanged(); - } - } - - /// Only the upload flow offers cancellation; restore keeps running once it starts. - public bool IsCloudUploading - { - get => _isCloudUploading; - private set - { - if (_isCloudUploading == value) - return; - - _isCloudUploading = value; - OnPropertyChanged(); - } - } - - /// - /// Disables the quota refresh command while the usage endpoint is being queried; the quota - /// label itself switches to the loading text for the same window. - /// - public bool IsCloudQuotaRefreshing - { - get => _isCloudQuotaRefreshing; - private set - { - if (_isCloudQuotaRefreshing == value) - return; - - _isCloudQuotaRefreshing = value; - OnPropertyChanged(); - } - } - - public string CloudAccountText - { - get => _cloudAccountText; - private set - { - if (_cloudAccountText == value) - return; - - _cloudAccountText = value; - OnPropertyChanged(); - } - } - - public string CloudQuotaText - { - get => _cloudQuotaText; - private set - { - if (_cloudQuotaText == value) - return; - - _cloudQuotaText = value; - OnPropertyChanged(); - } - } - - /// - /// Transient status shown next to the cloud list commands so a long list refresh or cleanup - /// purge still gives immediate feedback while both buttons are disabled. - /// - public string CloudListStatusText - { - get => _cloudListStatusText; - private set - { - if (_cloudListStatusText == value) - return; - - _cloudListStatusText = value; - OnPropertyChanged(); - } - } - public string BackupUsageText { get => _backupUsageText; @@ -243,23 +102,13 @@ event PropertyChangedEventHandler? INotifyPropertyChanged.PropertyChanged private void OnLoaded(object? sender, RoutedEventArgs e) { SubscribeSettings(); - SubscribeAccount(); - SubscribeCloudBackupEvents(); - if (IsCloudVisible) - { - // Entering the page always shows a current list and a current quota, so the page does not - // depend on the user pressing a refresh command first. - _ = RefreshCloudAsync(); - _ = RefreshCloudQuotaAsync(); - } + RefreshBackups(); } private void OnUnloaded(object? sender, RoutedEventArgs e) { UnsubscribeSettings(); UnsubscribeIncludeOptions(); - UnsubscribeAccount(); - UnsubscribeCloudBackupEvents(); } private void SettingsOnPropertyChanged(object? sender, PropertyChangedEventArgs e) @@ -293,7 +142,6 @@ private void SubscribeIncludeOptions() return; SelectedIncludeOptions.CollectionChanged += IncludeOptionsOnCollectionChanged; - SelectedCloudIncludeOptions.CollectionChanged += CloudIncludeOptionsOnCollectionChanged; _isIncludeOptionsSubscribed = true; } @@ -303,7 +151,6 @@ private void UnsubscribeIncludeOptions() return; SelectedIncludeOptions.CollectionChanged -= IncludeOptionsOnCollectionChanged; - SelectedCloudIncludeOptions.CollectionChanged -= CloudIncludeOptionsOnCollectionChanged; _isIncludeOptionsSubscribed = false; } @@ -344,9 +191,6 @@ private static AvaloniaList BuildSelectedOptions( private void IncludeOptionsOnCollectionChanged(object? sender, NotifyCollectionChangedEventArgs _) => ApplyIncludeSelection(IncludeOptions, SelectedIncludeOptions); - private void CloudIncludeOptionsOnCollectionChanged(object? sender, NotifyCollectionChangedEventArgs _) => - ApplyIncludeSelection(CloudIncludeOptions, SelectedCloudIncludeOptions); - private void ApplyIncludeSelection(IEnumerable options, IReadOnlyCollection selected) { @@ -358,484 +202,6 @@ private void ApplyIncludeSelection(IEnumerable options ConfigHandler.Save(); } - private void SubscribeAccount() - { - if (_authService is null || _isAccountSubscribed) - return; - - _authService.StateChanged += AccountOnStateChanged; - _isAccountSubscribed = true; - } - - private void UnsubscribeAccount() - { - if (_authService is null || !_isAccountSubscribed) - return; - - _authService.StateChanged -= AccountOnStateChanged; - _isAccountSubscribed = false; - } - - private void AccountOnStateChanged(object? sender, EventArgs e) => - Dispatcher.UIThread.Post(() => - { - _ = RefreshCloudAsync(); - _ = RefreshCloudQuotaAsync(); - }); - - private void SubscribeCloudBackupEvents() - { - if (_cloudBackupService is null || _isCloudEventSubscribed) - return; - - _cloudBackupService.AutomaticBackupUploaded += CloudBackupServiceOnAutomaticBackupUploaded; - _isCloudEventSubscribed = true; - } - - private void UnsubscribeCloudBackupEvents() - { - if (_cloudBackupService is null || !_isCloudEventSubscribed) - return; - - _cloudBackupService.AutomaticBackupUploaded -= CloudBackupServiceOnAutomaticBackupUploaded; - _isCloudEventSubscribed = false; - } - - /// - /// An automatic backup lands on a background thread and changes both the backup list and the - /// account quota, so an open page reloads them instead of showing stale values. - /// - private void CloudBackupServiceOnAutomaticBackupUploaded(object? sender, EventArgs e) => - Dispatcher.UIThread.Post(() => - { - _ = RefreshCloudAsync(); - _ = RefreshCloudQuotaAsync(); - }); - - private void RefreshCloudAccountPresentation() - { - bool signedIn = IsCloudSignedIn; - CloudAccountText = signedIn - ? string.Format(LR.C_CloudBackup_SignedInAs, - FirstNonBlank(_authService?.User?.ResolvedUserName, _authService?.Token?.UserId) ?? string.Empty) - : LR.C_CloudBackup_NotSignedIn; - OnPropertyChanged(nameof(IsCloudSignedIn)); - } - - /// - /// Reloads the cloud backup list. Cloud state is never cached in configuration; it is always - /// discovered from the signed-in account so several devices stay consistent. - /// - private async Task RefreshCloudAsync() - { - if (_cloudBackupService is null) - return; - - RefreshCloudAccountPresentation(); - if (!IsCloudSignedIn) - { - ClearCloudBackups(); - CloudQuotaText = string.Empty; - return; - } - - if (_isCloudRefreshing) - return; - - _isCloudRefreshing = true; - try - { - IReadOnlyList backups = await _cloudBackupService.ListAsync(); - _cloudDescriptors.Clear(); - CloudBackups.Clear(); - foreach (CloudBackupDescriptor descriptor in backups) - { - _cloudDescriptors[descriptor.BackupId] = descriptor; - CloudBackups.Add(ToRow(descriptor)); - } - } - catch (Exception ex) - { - _logger.LogError(ex, "获取云端备份列表失败。"); - this.ShowErrorToast(LR.M_CloudRefreshFailed); - } - finally - { - _isCloudRefreshing = false; - } - } - - /// - /// Quota is fetched on demand only: the usage endpoint scans the whole account and is much - /// slower than the file list, so page loads, list refreshes, and mutations must not wait for it. - /// - private async Task RefreshCloudQuotaAsync() - { - if (_cloudBackupService is null || !IsCloudSignedIn || _isCloudQuotaRefreshing) - return; - - IsCloudQuotaRefreshing = true; - CloudQuotaText = LR.M_CloudQuotaLoading; - try - { - SectlCloudQuota quota = await _cloudBackupService.GetQuotaAsync(); - CloudQuotaText = string.Format(LR.C_CloudBackup_QuotaUsage, FormatSize(quota.Used), - FormatSize(quota.Total), FormatSize(quota.PlatformUsed)); - } - catch (Exception quotaException) - { - _logger.LogWarning(quotaException, "获取云端空间用量失败。"); - CloudQuotaText = LR.M_CloudQuotaUnknown; - } - finally - { - IsCloudQuotaRefreshing = false; - } - } - - private void ClearCloudBackups() - { - _cloudDescriptors.Clear(); - CloudBackups.Clear(); - } - - private async void CloudSignIn_OnClick(object? sender, RoutedEventArgs e) - { - if (_authService is null || _isCloudBusy) - return; - - try - { - await _authService.SignInAsync(); - } - catch (Exception ex) - { - _logger.LogError(ex, "SECTL 账号登录失败。"); - await ShowErrorDialogAsync(LR.M_CloudSignedOut, ex.Message); - return; - } - - RefreshCloudAccountPresentation(); - await RefreshCloudAsync(); - } - - private async void CloudRefresh_OnClick(object? sender, RoutedEventArgs e) - { - if (_isCloudBusy) - return; - - CloudListStatusText = LR.M_CloudRefreshing; - try - { - await RefreshCloudAsync(); - await RefreshCloudQuotaAsync(); - } - finally - { - CloudListStatusText = string.Empty; - } - } - - private async void CloudQuotaRefresh_OnClick(object? sender, RoutedEventArgs e) - { - if (_cloudBackupService is null) - return; - if (!IsCloudSignedIn) - { - this.ShowWarningToast(LR.M_CloudSignInRequired); - return; - } - - await RefreshCloudQuotaAsync(); - } - - private void CloudStoragePage_OnClick(object? sender, RoutedEventArgs e) - { - if (!ExternalLauncher.TryOpenUri(CloudStoragePageUrl)) - this.ShowErrorToast(LR.M_CloudStoragePageFailed); - } - - private async void CloudUpload_OnClick(object? sender, RoutedEventArgs e) - { - if (_cloudBackupService is null || _isCloudBusy) - return; - if (!IsCloudSignedIn) - { - this.ShowWarningToast(LR.M_CloudSignInRequired); - return; - } - - // The upload is a plain verified upload now: account access is the only key, so nothing here - // can block on credentials beyond being signed in. - _cloudOperation = new CancellationTokenSource(); - SetCloudBusy(true, uploading: true); - try - { - await _cloudBackupService.UploadAsync(cancellationToken: _cloudOperation.Token); - this.ShowSuccessToast(LR.M_CloudUploadSuccess); - } - catch (OperationCanceledException) - { - this.ShowWarningToast(LR.M_CloudUploadCancelled); - } - catch (Exception ex) - { - _logger.LogError(ex, "云端备份上传失败。"); - await ShowErrorDialogAsync(LR.M_CloudUploadFailed, DescribeCloudUploadError(ex)); - } - finally - { - EndCloudOperation(); - // The upload row reports its own state, so the list refresh is what tells the user - // whether the new backup actually landed; it must run on success and on failure alike. - await RefreshCloudAsync(); - _ = RefreshCloudQuotaAsync(); - } - } - - private void CloudCancel_OnClick(object? sender, RoutedEventArgs e) - { - try - { - _cloudOperation?.Cancel(); - } - catch (ObjectDisposedException) - { - // The operation already finished; there is nothing left to cancel. - } - } - - private async void CloudCleanup_OnClick(object? sender, RoutedEventArgs e) - { - if (_cloudBackupService is null || _isCloudBusy) - return; - if (!IsCloudSignedIn) - { - this.ShowWarningToast(LR.M_CloudSignInRequired); - return; - } - - SetCloudBusy(true); - CloudListStatusText = LR.M_CloudCleaning; - try - { - int removed = await _cloudBackupService.PurgeIncompleteAsync(); - this.ShowSuccessToast(string.Format(LR.M_CloudCleanupSuccess, removed)); - } - catch (Exception ex) - { - _logger.LogError(ex, "清理不完整云端备份失败。"); - await ShowErrorDialogAsync(LR.M_CloudCleanupFailed, DescribeCloudError(ex)); - } - finally - { - EndCloudOperation(); - await RefreshCloudAsync(); - CloudListStatusText = string.Empty; - } - } - - private async void CloudRestoreBackup_OnClick(object? sender, RoutedEventArgs e) - { - if (_cloudBackupService is null || _isCloudBusy) - return; - if ((sender as Button)?.CommandParameter is not CloudBackupMetadata row) - return; - - CloudBackupDescriptor? descriptor = FindCloudDescriptor(row.BackupId); - if (descriptor is null || !descriptor.CanRestore) - { - // A package the removed encryption feature uploaded cannot be opened by this build at all, - // so it gets its own message instead of the generic "incomplete backup" one. - this.ShowWarningToast(descriptor?.IsEncrypted == true - ? LR.M_CloudLegacyEncrypted - : LR.M_CloudIncomplete); - await RefreshCloudAsync(); - return; - } - - if (!await ConfirmCloudRestoreAsync(row.DisplayName)) - return; - - _cloudOperation = new CancellationTokenSource(); - SetCloudBusy(true); - string? archivePath = null; - try - { - archivePath = await _cloudBackupService.DownloadAsync(descriptor, _cloudOperation.Token); - ImportInspection inspection = await _importExportService.InspectCloudBackupAsync(archivePath); - if (!inspection.IsSupportedV3) - { - await ShowErrorDialogAsync(LR.M_CloudRestoreFailed, - inspection.Warnings.FirstOrDefault() ?? LR.M_CloudIncomplete); - return; - } - - await _importExportService.ImportCloudBackupAsync(archivePath); - _logger.LogInformation("已恢复云端备份:备份={BackupId}。", descriptor.BackupId); - this.ShowSuccessToast(LR.M_CloudRestoreSuccess); - SettingsView.Current?.RequestRestartOrMobileReload(); - } - catch (OperationCanceledException) - { - this.ShowWarningToast(LR.M_CloudDownloadFailed); - } - catch (Exception ex) - { - _logger.LogError(ex, "恢复云端备份失败:备份={BackupId}。", descriptor.BackupId); - await ShowErrorDialogAsync(LR.M_CloudRestoreFailed, DescribeCloudError(ex)); - } - finally - { - EndCloudOperation(); - TryDeleteCloudArchive(archivePath); - } - } - - private async void CloudDeleteBackup_OnClick(object? sender, RoutedEventArgs e) - { - if (_cloudBackupService is null || _isCloudBusy) - return; - if ((sender as Button)?.CommandParameter is not CloudBackupMetadata row) - return; - - CloudBackupDescriptor? descriptor = FindCloudDescriptor(row.BackupId); - if (descriptor is null) - { - await RefreshCloudAsync(); - return; - } - - if (!await ConfirmCloudDeleteAsync(row.DisplayName)) - return; - - SetCloudBusy(true); - try - { - await _cloudBackupService.DeleteAsync(descriptor); - this.ShowSuccessToast(LR.M_CloudDeleteSuccess); - } - catch (Exception ex) - { - _logger.LogError(ex, "删除云端备份失败:备份={BackupId}。", descriptor.BackupId); - await ShowErrorDialogAsync(LR.M_CloudDeleteFailed, DescribeCloudError(ex)); - } - finally - { - EndCloudOperation(); - await RefreshCloudAsync(); - } - } - - private CloudBackupDescriptor? FindCloudDescriptor(string backupId) => - _cloudDescriptors.GetValueOrDefault(backupId); - - private void SetCloudBusy(bool value, bool uploading = false) - { - IsCloudUploading = uploading; - IsCloudBusy = value; - } - - private void EndCloudOperation() - { - _cloudOperation?.Dispose(); - _cloudOperation = null; - IsCloudUploading = false; - IsCloudBusy = false; - } - - private static CloudBackupMetadata ToRow(CloudBackupDescriptor descriptor) => new() - { - BackupId = descriptor.BackupId, - DisplayName = descriptor.DisplayName, - DateTime = descriptor.CreatedAt?.LocalDateTime ?? DateTime.MinValue, - Size = FormatSize(descriptor.TotalBytes), - IsComplete = descriptor.IsComplete, - PartCount = descriptor.PartCount, - // A legacy encrypted package is flagged in the file-name cell: it is listed so the user can see - // and delete it, but it can never be restored by a build that holds no passphrase key. - IsLegacyEncrypted = descriptor.IsEncrypted, - StatusText = descriptor.IsEncrypted - ? LR.C_CloudBackup_LegacyEncrypted - : descriptor.IsComplete - ? string.Empty - : LR.C_CloudBackup_Incomplete - }; - - /// Maps cloud service error codes onto localized guidance instead of raw API text. - private static string DescribeCloudError(Exception exception) => exception switch - { - SectlCloudStorageException { Code: "storage_exceeded" } => LR.M_CloudQuotaExceeded, - SectlCloudStorageException { Code: "cloud_service_disabled" or "insufficient_scope" } => LR.M_CloudServiceDisabled, - SectlCloudStorageException { Code: "invalid_token" or "unauthorized" } => LR.M_CloudSignedOut, - SectlCloudStorageException { Code: "cloud_timeout" } => LR.M_CloudServerTimeout, - SectlCloudStorageException { Code: "internal_error" or "upload_failed" or "invalid_response" } => LR.M_CloudServerError, - InvalidOperationException => LR.M_CloudSignedOut, - _ => exception.Message - }; - - /// - /// A timed-out upload may still have created parts on the server after the gateway gave up, - /// so the failure text points at the cleanup action instead of leaving that state unexplained. - /// - private static string DescribeCloudUploadError(Exception exception) - { - var detail = DescribeCloudError(exception); - return exception is SectlCloudStorageException { Code: "cloud_timeout" or "internal_error" or "upload_failed" } - ? $"{detail}\n{LR.M_CloudUploadCleanupHint}" - : detail; - } - - private static void TryDeleteCloudArchive(string? path) - { - if (string.IsNullOrWhiteSpace(path)) - return; - - try - { - if (File.Exists(path)) - File.Delete(path); - } - catch (IOException) - { - // The staging archive stays under data/cache and is never part of an export root. - } - catch (UnauthorizedAccessException) - { - } - } - - private static string? FirstNonBlank(params string?[] values) => - values.FirstOrDefault(value => !string.IsNullOrWhiteSpace(value))?.Trim(); - - private async Task ConfirmCloudRestoreAsync(string displayName) - { - var result = await new FAContentDialog - { - Title = LR.M_CloudRestoreTitle, - Content = string.Format(LR.M_CloudRestoreContent, displayName), - PrimaryButtonText = LR.M_RestorePrimary, - CloseButtonText = LR.C_Cancel, - DefaultButton = FAContentDialogButton.Close - }.ShowAsync(TopLevel.GetTopLevel(this)); - - return result == FAContentDialogResult.Primary; - } - - private async Task ConfirmCloudDeleteAsync(string displayName) - { - var result = await new FAContentDialog - { - Title = LR.M_CloudDeleteTitle, - Content = string.Format(LR.M_CloudDeleteContent, displayName), - PrimaryButtonText = LR.M_DeletePrimary, - CloseButtonText = LR.C_Cancel, - DefaultButton = FAContentDialogButton.Close - }.ShowAsync(TopLevel.GetTopLevel(this)); - - return result == FAContentDialogResult.Primary; - } - private async void ManualBackup_OnClick(object? sender, RoutedEventArgs e) { try @@ -992,7 +358,6 @@ private static string GetBackupDirectory() return Utils.GetDirectoryPath(BackupDirectoryName); } - private static string FormatSize(long bytes) { string[] units = ["B", "KB", "MB", "GB"]; @@ -1014,4 +379,4 @@ private void OnPropertyChanged([CallerMemberName] string? propertyName = null) { NotifyPropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } -} +} \ No newline at end of file diff --git a/SecRandom/Views/SettingsPages/General/SecuritySettingsPage.axaml b/SecRandom/Views/SettingsPages/General/SecuritySettingsPage.axaml index 90c429031..da6d73fd0 100644 --- a/SecRandom/Views/SettingsPages/General/SecuritySettingsPage.axaml +++ b/SecRandom/Views/SettingsPages/General/SecuritySettingsPage.axaml @@ -236,47 +236,7 @@ IsEnabled="{Binding CanEditProtectedOperations}" /> - - - - - - - - - - - - - - - - - - - - + (FactorOptions.Where(option => option.IsSelected)); SelectedFactorOptions.CollectionChanged += SelectedFactorOptionsOnCollectionChanged; - IntegrityActionOptions = - [ - new(SettingsIntegrityAction.Confirm, SR.O_IntegrityAction_Confirm), - new(SettingsIntegrityAction.AutoRestore, SR.O_IntegrityAction_AutoRestore) - ]; - IntegrityRestoreSourceOptions = - [ - new(SettingsIntegrityRestoreSource.Local, SR.O_IntegrityRestoreSource_Local), - new(SettingsIntegrityRestoreSource.LocalThenCloud, SR.O_IntegrityRestoreSource_LocalThenCloud), - new(SettingsIntegrityRestoreSource.CloudThenLocal, SR.O_IntegrityRestoreSource_CloudThenLocal) - ]; DataContext = this; InitializeComponent(); SubscribeSettings(); @@ -61,11 +49,6 @@ public SecuritySettingsPage() public SecuritySettingsConfig Settings { get; } public AvaloniaList FactorOptions { get; } public AvaloniaList SelectedFactorOptions { get; } - public AvaloniaList> IntegrityActionOptions { get; } - public AvaloniaList> IntegrityRestoreSourceOptions { get; } - public SettingOption? SelectedIntegrityActionOption { get; private set; } - public SettingOption? SelectedIntegrityRestoreSourceOption { get; private set; } - public bool IsAutoRestoreSelected => Settings.SettingsIntegrityAction == SettingsIntegrityAction.AutoRestore; public bool CanEnableSecurity { get; private set; } public bool IsSecurityEnabled { get; private set; } public bool HasPassword { get; private set; } @@ -170,12 +153,6 @@ private void RefreshSecurityState() ? string.Format(SR.M_LockoutFormat, Math.Ceiling(remaining.TotalSeconds)) : string.Empty; SudoModeDurationValue = Settings.SudoModeDurationSeconds; - // 配置可能被手工改写成未知枚举值,这里回退到默认项而不是让下拉框绑定抛异常 - SelectedIntegrityActionOption = IntegrityActionOptions - .FirstOrDefault(option => option.Value == Settings.SettingsIntegrityAction) ?? IntegrityActionOptions[0]; - SelectedIntegrityRestoreSourceOption = IntegrityRestoreSourceOptions - .FirstOrDefault(option => option.Value == Settings.SettingsIntegrityRestoreSource) - ?? IntegrityRestoreSourceOptions[0]; SynchronizeSelectedFactorOptions(); } finally @@ -187,9 +164,7 @@ private void RefreshSecurityState() nameof(HasTotp), nameof(CanConfigureAdditionalFactors), nameof(CanEditFactorSelection), nameof(CanEditProtectedOperations), nameof(TotpButtonText), nameof(IsLockedOut), nameof(LockoutText), - nameof(SudoModeDurationValue), nameof(CanEditSudoModeDuration), - nameof(SelectedIntegrityActionOption), nameof(SelectedIntegrityRestoreSourceOption), - nameof(IsAutoRestoreSelected) + nameof(SudoModeDurationValue), nameof(CanEditSudoModeDuration) }) NotifyPropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name)); } @@ -236,47 +211,6 @@ await ApplySecuritySettingsUpdateAsync( () => toggle.IsChecked = current); } - /// - /// 篡改处理方式与恢复来源共用一套流程:先按旧值回退下拉框,再走安全密码授权后写入设置。 - /// - private async void IntegrityAction_OnSelectionChanged(object? sender, SelectionChangedEventArgs e) - { - if (_refreshing || sender is not ComboBox combo || - combo.SelectedItem is not SettingOption option || - option.Value == Settings.SettingsIntegrityAction) - return; - - if (TopLevel.GetTopLevel(this) is not { } xamlRoot) - { - RefreshSecurityState(); - return; - } - - await ApplySecuritySettingsUpdateAsync( - xamlRoot, - () => Settings.SettingsIntegrityAction = option.Value, - () => combo.SelectedItem = SelectedIntegrityActionOption); - } - - private async void IntegrityRestoreSource_OnSelectionChanged(object? sender, SelectionChangedEventArgs e) - { - if (_refreshing || sender is not ComboBox combo || - combo.SelectedItem is not SettingOption option || - option.Value == Settings.SettingsIntegrityRestoreSource) - return; - - if (TopLevel.GetTopLevel(this) is not { } xamlRoot) - { - RefreshSecurityState(); - return; - } - - await ApplySecuritySettingsUpdateAsync( - xamlRoot, - () => Settings.SettingsIntegrityRestoreSource = option.Value, - () => combo.SelectedItem = SelectedIntegrityRestoreSourceOption); - } - private async void SetPassword_OnClick(object? sender, RoutedEventArgs e) { if (TopLevel.GetTopLevel(this) is not { } xamlRoot) return; @@ -429,10 +363,6 @@ private bool TryGetSecurityOption(string optionName, out Func getValue, ou getValue = () => Settings.AllowSettingsPreview; setValue = value => Settings.AllowSettingsPreview = value; return true; - case nameof(SecuritySettingsConfig.SettingsIntegrityCheckEnabled): - getValue = () => Settings.SettingsIntegrityCheckEnabled; - setValue = value => Settings.SettingsIntegrityCheckEnabled = value; - return true; case nameof(SecuritySettingsConfig.ProtectOpenSettings): getValue = () => Settings.ProtectOpenSettings; setValue = value => Settings.ProtectOpenSettings = value; diff --git a/SecRandom/Views/SettingsPages/General/VerificationSettingsPage.axaml b/SecRandom/Views/SettingsPages/General/VerificationSettingsPage.axaml index e5a079c5a..8425807a9 100644 --- a/SecRandom/Views/SettingsPages/General/VerificationSettingsPage.axaml +++ b/SecRandom/Views/SettingsPages/General/VerificationSettingsPage.axaml @@ -59,23 +59,6 @@ - - - - - /// - /// 为 true 时是"左右两侧显示"开启后出现在右边缘的副窗。副窗与主窗共用同一套按钮、 - /// 停靠与联动逻辑,但只保存自己的纵向锚点:横向位置永远由角色决定(主窗在左、副窗在右), - /// 不写共享的 ,否则两扇窗会互相覆盖位置。 + /// 为 true 时是"左右两侧显示"开启后补在另一侧的那扇窗;主窗则留在它原本所在的那一侧。 + /// 副窗与主窗共用同一套按钮、停靠与联动逻辑,但只保存自己的纵向锚点:横向位置永远由角色 + /// (主窗在哪侧、副窗就在另一侧)决定,不写共享的 , + /// 否则两扇窗会互相覆盖位置。 /// public FloatingWindow(bool isSecondary) { @@ -142,6 +143,35 @@ private void OnWindowPropertyChanged(object? sender, AvaloniaPropertyChangedEven public bool IsSecondary => _isSecondary; public bool IsEdgePinned => _edgePinned; + /// + /// 窗口此刻所在的横向半区:true 表示所在屏幕的左半区。 + /// + /// + /// "左右两侧同时显示"靠它决定主窗留在哪一侧:用户原本把单扇浮窗放在左边,开启两侧显示后 + /// 主窗就不该跳到右边,否则关掉开关后窗口会停在与原来相反的一侧。钉边/停靠状态优先, + /// 因为这两种状态下窗口已经被强制贴在自己那一侧;其余情况按窗口中心与该屏工作区中心比较, + /// 与停靠判定用的是同一条中线规则。 + /// + public bool IsOnLeftSide + { + get + { + if (_edgePinned) + return _pinnedOnLeft; + + if (_isDocked) + return _isDockedOnLeft; + + var width = Math.Max(1, (int)Math.Ceiling(Bounds.Width * RenderScaling)); + var height = Math.Max(1, (int)Math.Ceiling(Bounds.Height * RenderScaling)); + var workingArea = GetScreenForWindow(Position, width, height)?.WorkingArea; + if (workingArea is not { } area) + return false; + + return Position.X + width / 2 <= area.Center.X; + } + } + /// 当前窗口中心的屏幕 Y 坐标;停靠态用停靠锚点。 public int AnchorCenterY { @@ -170,9 +200,9 @@ public int AnchorCenterY /// 是否钉边。 /// 钉在哪一侧;解除钉住时忽略。 /// - /// 钉边是"左右两侧显示"的交互约束:开启后主窗固定在右边缘、副窗固定在左边缘, + /// 钉边是"左右两侧显示"的交互约束:开启后主窗钉在它原本那一侧、副窗钉在另一侧, /// 用户只能纵向移动,不能被拖到屏幕中间或换到另一侧。解除钉住后恢复原来的吸附/自由拖动行为。 - /// 主窗固定在右侧,是因为关掉"左右两侧同时显示"后要保留的就是右侧那扇主窗。 + /// 主窗留在自己原本那一侧(而不是固定右侧),这样关掉"左右两侧同时显示"后窗口才回得到原来那一侧。 /// public void SetEdgePinned(bool pinned, bool onLeft) { @@ -1470,8 +1500,8 @@ private void SavePosition() var unifiedAnchor = settings.ShowOnBothSides && settings.SyncBothSidesAnchor; var anchorCenterY = AnchorCenterY; - // 副窗只记住自己的纵向锚点:横向位置由"副窗在右"这个角色决定,写共享的 FloatPosition - // 会让两扇窗在下次启动时抢同一个坐标。 + // 副窗只记住自己的纵向锚点:横向位置由"主窗在哪侧、副窗就在另一侧"这个角色决定, + // 写共享的 FloatPosition 会让两扇窗在下次启动时抢同一个坐标。 if (_isSecondary) { settings.SecondaryAnchorCenterY = anchorCenterY; From f7ba023f1e4c4cb85d10bd1afd947de6f113f08e Mon Sep 17 00:00:00 2001 From: lzy98276 Date: Sat, 14 Nov 2026 19:31:18 +0800 Subject: [PATCH 05/26] =?UTF-8?q?feat(notification):=20=E6=B5=AE=E7=AA=97?= =?UTF-8?q?=E9=80=9A=E7=9F=A5=E6=8C=89=E6=A1=8C=E9=9D=A2=E4=BA=AE=E5=BA=A6?= =?UTF-8?q?=E8=87=AA=E9=80=82=E5=BA=94=E5=89=8D=E6=99=AF=E8=89=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 平台层新增一次性屏幕亮度采样(IScreenLuminanceSampler):Windows 走 GDI BitBlt + 亮度直方图,其它平台回退 Unsupported,绝不当作截屏流 - Core 新增 AdaptiveTheme/AdaptiveBackdropResolver,按亮度分位决定白/黑前景与 scrim 不透明度,文字对比度不低于 WCAG 4.5:1 - 通知窗显示前并行建窗与采样:60ms 超时,窗口以 Opacity=0 占位后 90ms 淡入,采样失败回退应用主题 - 新增开关 NotificationSettings.Default.AdaptiveForeground(默认开启;低配模式下置灰显示为关且不改写用户偏好,采样同样跳过) - 全屏通知的动画样式与背景模糊在低配下置灰并显示实际生效值,与开关同规则 - 内置通知浮窗的窗口几何收归独立设置页,渠道页不再重复同一组控件 --- SecRandom.Core.Tests/AdaptiveBackdropTests.cs | 85 +++++ .../SubConfigs/NotificationSettingsConfig.cs | 126 +++++++ .../Services/Presentation/AdaptiveTheme.cs | 163 +++++++++ SecRandom.Platforms.Abstractions/AGENTS.md | 1 + .../IPlatformServiceRoot.cs | 3 + .../ScreenLuminance.cs | 80 +++++ .../LinuxPlatformServiceRoot.cs | 2 + .../MacOsPlatformServiceRoot.cs | 2 + .../WindowsPlatformServiceRoot.cs | 2 + .../WindowsScreenLuminanceSampler.cs | 301 +++++++++++++++++ .../PlatformServiceRootStub.cs | 2 + SecRandom/Helpers/DrawColorHelper.cs | 7 +- SecRandom/Helpers/UiRenderQuality.cs | 5 +- .../Notification/Resources.Designer.cs | 309 +++--------------- .../Notification/Resources.en-US.resx | 10 +- .../Notification/Resources.ja-JP.resx | 10 +- .../SettingsPages/Notification/Resources.resx | 114 +------ .../MainPages/QuickDrawPageViewModel.cs | 25 +- .../Views/MainPages/QuickDrawPage.axaml.cs | 115 ++++++- .../DefaultNotificationSettingsPage.axaml | 63 ---- .../DefaultNotificationSettingsPage.axaml.cs | 6 - .../FullscreenNotificationSettingsPage.axaml | 8 +- ...ullscreenNotificationSettingsPage.axaml.cs | 38 ++- .../NotificationChannelSettingsContent.axaml | 67 ---- .../NotificationChannelSettingsPageBase.cs | 72 ---- ...tificationFloatingWindowSettingsPage.axaml | 90 +++++ ...icationFloatingWindowSettingsPage.axaml.cs | 188 +++++++++++ 27 files changed, 1299 insertions(+), 595 deletions(-) create mode 100644 SecRandom.Core.Tests/AdaptiveBackdropTests.cs create mode 100644 SecRandom.Core/Services/Presentation/AdaptiveTheme.cs create mode 100644 SecRandom.Platforms.Abstractions/ScreenLuminance.cs create mode 100644 SecRandom.Platforms.Windows/WindowsScreenLuminanceSampler.cs create mode 100644 SecRandom/Views/SettingsPages/Notification/NotificationFloatingWindowSettingsPage.axaml create mode 100644 SecRandom/Views/SettingsPages/Notification/NotificationFloatingWindowSettingsPage.axaml.cs diff --git a/SecRandom.Core.Tests/AdaptiveBackdropTests.cs b/SecRandom.Core.Tests/AdaptiveBackdropTests.cs new file mode 100644 index 000000000..d5fd0d228 --- /dev/null +++ b/SecRandom.Core.Tests/AdaptiveBackdropTests.cs @@ -0,0 +1,85 @@ +using Avalonia.Media; +using SecRandom.Core.Services.Presentation; + +namespace SecRandom.Core.Tests; + +public class AdaptiveBackdropTests +{ + [Theory] + [InlineData(0.00)] + [InlineData(0.10)] + [InlineData(0.35)] + [InlineData(0.50)] + [InlineData(0.65)] + [InlineData(0.90)] + [InlineData(1.00)] + public void KeepsReadableContrastAcrossTheWholeLuminanceRange(double median) + { + var theme = AdaptiveBackdropResolver.Resolve( + BackdropLuminance.FromPercentiles(median, median, median), appThemeIsDark: false); + + Assert.True( + AdaptiveBackdropResolver.ContrastAgainstSurface(theme) >= AdaptiveBackdropResolver.MinimumContrastRatio, + $"median={median:0.00} contrast={AdaptiveBackdropResolver.ContrastAgainstSurface(theme):0.00}"); + } + + [Fact] + public void PicksWhiteTextOnADarkDesktop() + { + var theme = AdaptiveBackdropResolver.Resolve( + BackdropLuminance.FromPercentiles(0.01, 0.05, 0.09), appThemeIsDark: false); + + Assert.True(theme.IsDarkBackdrop); + Assert.Equal(Colors.White, theme.Foreground); + } + + [Fact] + public void PicksBlackTextOnABrightDesktop() + { + var theme = AdaptiveBackdropResolver.Resolve( + BackdropLuminance.FromPercentiles(0.85, 0.93, 0.99), appThemeIsDark: true); + + Assert.False(theme.IsDarkBackdrop); + Assert.Equal(Colors.Black, theme.Foreground); + } + + [Fact] + public void PressesTheSurfaceHarderWhenTheBackdropIsBusy() + { + var flat = AdaptiveBackdropResolver.Resolve( + BackdropLuminance.FromPercentiles(0.30, 0.35, 0.40), appThemeIsDark: false); + var busy = AdaptiveBackdropResolver.Resolve( + BackdropLuminance.FromPercentiles(0.02, 0.35, 0.95), appThemeIsDark: false); + + Assert.True(busy.SurfaceAlpha > flat.SurfaceAlpha); + } + + [Fact] + public void CardSurfaceIsAtLeastAsOpaqueAsTheRootSurface() + { + var theme = AdaptiveBackdropResolver.Resolve( + BackdropLuminance.FromPercentiles(0.2, 0.3, 0.4), appThemeIsDark: false); + + Assert.True(theme.CardSurface.A >= theme.Surface.A); + Assert.True(theme.Surface.A < 255); + } + + [Fact] + public void FallsBackToAnOpaqueCardMatchingTheAppTheme() + { + var dark = AdaptiveBackdropResolver.FromAppTheme(isDarkTheme: true); + var light = AdaptiveBackdropResolver.FromAppTheme(isDarkTheme: false); + + Assert.Equal(255, dark.Surface.A); + Assert.Equal(255, light.Surface.A); + Assert.Equal(Colors.White, dark.Foreground); + Assert.Equal(Colors.Black, light.Foreground); + } + + [Fact] + public void ContrastUsesTheWcagFormula() + { + Assert.Equal(21.0, AdaptiveBackdropResolver.ContrastRatio(0, Colors.White), 3); + Assert.Equal(1.0, AdaptiveBackdropResolver.ContrastRatio(0.0, Colors.Black), 3); + } +} \ No newline at end of file diff --git a/SecRandom.Core/Models/SubConfigs/NotificationSettingsConfig.cs b/SecRandom.Core/Models/SubConfigs/NotificationSettingsConfig.cs index 5ba422648..a807313b1 100644 --- a/SecRandom.Core/Models/SubConfigs/NotificationSettingsConfig.cs +++ b/SecRandom.Core/Models/SubConfigs/NotificationSettingsConfig.cs @@ -1,5 +1,6 @@ using System.Diagnostics.CodeAnalysis; using System.Text.Json.Serialization; +using Avalonia.Media; using CommunityToolkit.Mvvm.ComponentModel; namespace SecRandom.Core.Models.SubConfigs; @@ -11,6 +12,8 @@ public partial class NotificationSettingsConfig : ObservableObject, IJsonOnDeser private bool _overrideDefaultsInitialized = true; private bool _hasBasicSettingsSeparatedInitialized; private bool _basicSettingsSeparatedInitialized = true; + private bool _hasFloatingWindowSettingsUnifiedInitialized; + private bool _floatingWindowSettingsUnifiedInitialized = true; private NotificationChannelSettings _default = NotificationChannelSettings.CreateDisabled(); private OverridableNotificationChannelSettings _rollCall = new(); private OverridableNotificationChannelSettings _quickDraw = CreateQuickDraw(); @@ -86,6 +89,25 @@ private set } } + /// + /// 内置通知浮窗的窗口设置(位置 / 显示器 / 偏移 / 不透明度)已从各渠道设置页收归独立的 + /// 「内置通知浮窗」页面,并且只写 ,所以渠道的窗口覆盖不再有入口。 + /// + /// + /// 旧配置里手工打开的分渠道窗口覆盖在这里折回默认设置,否则会出现一个「看不见也改不掉」的覆盖: + /// 新页面改的是 Default,而该渠道仍然读自己的旧窗口值。标记本身只在迁移时写一次。 + /// + [JsonInclude] + public bool FloatingWindowSettingsUnifiedInitialized + { + get => _floatingWindowSettingsUnifiedInitialized; + private set + { + _hasFloatingWindowSettingsUnifiedInitialized = true; + _floatingWindowSettingsUnifiedInitialized = value; + } + } + private static OverridableNotificationChannelSettings CreateQuickDraw() { var settings = OverridableNotificationChannelSettings.CreateEnabled(); @@ -111,6 +133,14 @@ void IJsonOnDeserialized.OnDeserialized() _overrideDefaultsInitialized = true; } + if (!_hasFloatingWindowSettingsUnifiedInitialized || !_floatingWindowSettingsUnifiedInitialized) + { + RollCall.OverrideNotificationWindowSettings = false; + QuickDraw.OverrideNotificationWindowSettings = false; + Lottery.OverrideNotificationWindowSettings = false; + _floatingWindowSettingsUnifiedInitialized = true; + } + if (_hasBasicSettingsSeparatedInitialized && _basicSettingsSeparatedInitialized) return; @@ -148,6 +178,16 @@ public partial class NotificationChannelSettings : ObservableObject, IJsonOnDese [ObservableProperty] private int _horizontalOffset = 0; [ObservableProperty] private int _verticalOffset = 0; [ObservableProperty] private int _transparency = 80; + + /// + /// 内置通知浮窗是否按窗口背后的桌面亮度自适应前景色(默认开启)。 + /// + /// + /// 只在采样成功时生效:抓不到桌面(非 Windows、锁屏、远程桌面)就回退应用主题。 + /// 低配模式会强制关闭这一项(DWM 合成与逐像素采样都不该在低配机上跑), + /// 设置页因此把开关置灰并显示为关闭。 + /// + [ObservableProperty] private bool _adaptiveForeground = true; private int _notificationServiceType; [ObservableProperty] private int _displayDuration = 3; private bool _hasDisplayDuration; @@ -158,6 +198,11 @@ public partial class NotificationChannelSettings : ObservableObject, IJsonOnDese [ObservableProperty] private bool _useMainWindowWhenExceedThreshold = true; [ObservableProperty] private int _mainWindowDisplayThreshold = 5; + private int _countdownStyle = (int)NotificationCountdownStyle.Edge; + private int _countdownColorMode = (int)NotificationCountdownColorMode.Gradient; + private Color _countdownSolidColor = NotificationCountdownPalette.DefaultStart; + private List _countdownGradientColors = NotificationCountdownPalette.CreateDefaultColors(); + public bool UseBuiltInOnServiceFailure { get => _useBuiltInOnServiceFailure; @@ -224,6 +269,58 @@ public int NotificationServiceType [JsonIgnore] public bool UsesFullscreenNotificationService => NotificationServiceType == 3; + /// + /// 内置通知浮窗的倒计时样式:0 = 文字提示,1 = 四周描边。 + /// + /// + /// 和浮窗几何一样是全局外观,只读 , + /// 但字段仍留在共享的渠道设置类型上(既有 等也是这个形态)。 + /// 默认值由字段初始化器给出,所以旧配置缺这个键时直接是新样式,不需要迁移代码。 + /// + public int CountdownStyle + { + get => _countdownStyle; + set => SetProperty( + ref _countdownStyle, + value is (int)NotificationCountdownStyle.Text or (int)NotificationCountdownStyle.Edge + ? value + : (int)NotificationCountdownStyle.Edge); + } + + /// 倒计时颜色模式:0 = 渐变,1 = 纯色。 + public int CountdownColorMode + { + get => _countdownColorMode; + set => SetProperty( + ref _countdownColorMode, + value is (int)NotificationCountdownColorMode.Gradient or (int)NotificationCountdownColorMode.Solid + ? value + : (int)NotificationCountdownColorMode.Gradient); + } + + /// 纯色模式的描边颜色;透明度归一为不透明,浮窗整体透明度另有设置。 + public Color CountdownSolidColor + { + get => _countdownSolidColor; + set => SetProperty(ref _countdownSolidColor, NotificationCountdownPalette.ToOpaque(value)); + } + + /// 渐变模式的色标,顺序即「右上角 → 左下角」的颜色顺序。 + public List CountdownGradientColors + { + get => _countdownGradientColors; + set => SetProperty(ref _countdownGradientColors, NotificationCountdownPalette.NormalizeColors(value)); + } + + [JsonIgnore] + public bool UsesEdgeCountdown => CountdownStyle == (int)NotificationCountdownStyle.Edge; + + [JsonIgnore] + public IReadOnlyList ResolvedCountdownColors => + CountdownColorMode == (int)NotificationCountdownColorMode.Solid + ? [CountdownSolidColor] + : CountdownGradientColors; + public bool Enabled { get => _enabled; @@ -260,6 +357,18 @@ void IJsonOnDeserialized.OnDeserialized() if (!_hasUseBuiltInOnServiceFailure && _legacyUseBuiltInOnClassIslandFailure is { } legacyValue) _useBuiltInOnServiceFailure = legacyValue; + // 手改/旧版配置文件里的越界值在这里兜底;字段初始化器已保证缺键时采用新倒计时。 + _countdownStyle = _countdownStyle + is (int)NotificationCountdownStyle.Text or (int)NotificationCountdownStyle.Edge + ? _countdownStyle + : (int)NotificationCountdownStyle.Edge; + _countdownColorMode = _countdownColorMode + is (int)NotificationCountdownColorMode.Gradient or (int)NotificationCountdownColorMode.Solid + ? _countdownColorMode + : (int)NotificationCountdownColorMode.Gradient; + _countdownGradientColors = NotificationCountdownPalette.NormalizeColors(_countdownGradientColors); + _countdownSolidColor = NotificationCountdownPalette.ToOpaque(_countdownSolidColor); + _legacyAutoCloseTime = null; _legacyUseBuiltInOnClassIslandFailure = null; } @@ -295,3 +404,20 @@ public static OverridableNotificationChannelSettings CreateEnabled() return settings; } } + +/// 内置通知浮窗的倒计时样式。 +public enum NotificationCountdownStyle +{ + /// 结果区的文字秒数提示(旧行为)。 + Text = 0, + + /// 沿浮窗四周收缩的描边(默认)。 + Edge = 1 +} + +/// 倒计时描边的配色模式。 +public enum NotificationCountdownColorMode +{ + Gradient = 0, + Solid = 1 +} diff --git a/SecRandom.Core/Services/Presentation/AdaptiveTheme.cs b/SecRandom.Core/Services/Presentation/AdaptiveTheme.cs new file mode 100644 index 000000000..63ca39539 --- /dev/null +++ b/SecRandom.Core/Services/Presentation/AdaptiveTheme.cs @@ -0,0 +1,163 @@ +using Avalonia.Media; + +namespace SecRandom.Core.Services.Presentation; + +/// +/// 一块背景的亮度分布(线性相对亮度,0–1)。 +/// +/// +/// 这是 在 Core 侧的中性投影。 +/// Core 不引用平台工程,所以平台采样结果必须先降成这三个数再交给判定逻辑;这也让判定逻辑 +/// 可以完全不碰 Avalonia 之外的任何东西,直接单测。 +/// +public readonly record struct BackdropLuminance(double P10, double Median, double P90) +{ + public double Spread => Math.Max(0, P90 - P10); + + public static BackdropLuminance FromPercentiles(double p10, double median, double p90) => + new(Clamp01(p10), Clamp01(median), Clamp01(p90)); + + private static double Clamp01(double value) => double.IsNaN(value) ? 0 : Math.Clamp(value, 0, 1); +} + +/// +/// 一次展示使用的自适应前景/底色方案。 +/// +/// +/// 与 都带透明度:卡片压在采样到的桌面上, +/// 而不是替换成一块不透明色,这样"自适应"才真的看得见桌面。前景色是针对合成之后的结果 +/// 算出来的,所以它对 的对比度一定达标。 +/// +public sealed record AdaptiveTheme( + bool IsDarkBackdrop, + Color Foreground, + Color SecondaryForeground, + Color Stroke, + Color Surface, + Color CardSurface, + Color AvatarSurface, + double SurfaceLuminance) +{ + /// 卡片底色的不透明度(0–1)。 + public double SurfaceAlpha => Surface.A / 255d; +} + +/// +/// 把"背景有多亮"翻译成"用白字还是黑字、卡片底压多深"。 +/// +/// +/// +/// 只用两种前景(白/黑)是刻意的:这正是"自适应主题色"的需求本身,也是唯一在 HDR/广色域/ +/// 远程桌面下都稳的判据。所有中间色、强调色都由既有主题体系负责,这里不引入第三种前景。 +/// +/// +/// 判定顺序:先按中位数选深/浅,再用亮度离散度决定要不要把底压得更实(花壁纸、PPT 视频背景 +/// 的亮度跨度很大,同一个中位数下文字可能局部不可读),最后用 WCAG 对比度兜一次底。 +/// +/// +public static class AdaptiveBackdropResolver +{ + /// 正文与卡片底之间必须达到的对比度(WCAG AA 正文标准)。 + public const double MinimumContrastRatio = 4.5; + + /// 中位数低于它就算深色背景。 + public const double DarkBackdropThreshold = 0.5; + + /// 背景亮度跨度过大时把卡片底压得更实,避免局部文字与背景同色。 + public const double HighSpreadThreshold = 0.5; + + public const double DefaultSurfaceAlpha = 0.82; + public const double HighSpreadSurfaceAlpha = 0.88; + public const double ContrastGateSurfaceAlpha = 0.92; + + private const double CardSurfaceAlphaBonus = 0.08; + private const byte SecondaryAlpha = 0xCC; + private const byte StrokeAlpha = 0x26; + private const byte AvatarAlpha = 0x33; + + private static readonly Color DarkSurfaceColor = Color.FromRgb(0x1F, 0x1F, 0x1F); + private static readonly Color LightSurfaceColor = Color.FromRgb(0xFA, 0xFA, 0xFA); + + /// 没有采样能力或采样失败时的回退方案:与应用主题一致的实色卡片(即今天的外观)。 + public static AdaptiveTheme FromAppTheme(bool isDarkTheme) + { + var surface = isDarkTheme ? DarkSurfaceColor : LightSurfaceColor; + return Build(isDarkTheme, 1.0, RelativeLuminance(surface)); + } + + /// + /// 按背景亮度分布求解自适应方案。 只在亮度中位数恰好 + /// 落在分界线上时充当平局判定,正常情况完全由桌面决定。 + /// + public static AdaptiveTheme Resolve(BackdropLuminance backdrop, bool appThemeIsDark) + { + var median = backdrop.Median; + var isDark = Math.Abs(median - DarkBackdropThreshold) < 0.0001 + ? appThemeIsDark + : median < DarkBackdropThreshold; + + var alpha = backdrop.Spread >= HighSpreadThreshold + ? HighSpreadSurfaceAlpha + : DefaultSurfaceAlpha; + + var theme = Build(isDark, alpha, median); + if (ContrastAgainstSurface(theme) >= MinimumContrastRatio) + return theme; + + // 对比度不够只可能出现在"半透明底 + 中灰背景"的窄带上:把底压得更实再算一次, + // 还不够就直接不透明(此时回到应用主题的安全外观,但前景仍是按背景选的)。 + theme = Build(isDark, ContrastGateSurfaceAlpha, median); + if (ContrastAgainstSurface(theme) >= MinimumContrastRatio) + return theme; + + return Build(isDark, 1.0, median); + } + + /// 前景色与"卡片底合成到背景之后"的对比度。 + public static double ContrastAgainstSurface(AdaptiveTheme theme) => + ContrastRatio(theme.SurfaceLuminance, theme.Foreground); + + /// WCAG 相对亮度(输入已经是 0–1 线性亮度)。 + public static double ContrastRatio(double backgroundLuminance, Color foreground) + { + var foregroundLuminance = RelativeLuminance(foreground); + var lighter = Math.Max(backgroundLuminance, foregroundLuminance); + var darker = Math.Min(backgroundLuminance, foregroundLuminance); + return (lighter + 0.05) / (darker + 0.05); + } + + /// sRGB 颜色 → 线性相对亮度(WCAG 定义)。 + public static double RelativeLuminance(Color color) => + 0.2126 * Linearize(color.R) + 0.7152 * Linearize(color.G) + 0.0722 * Linearize(color.B); + + private static AdaptiveTheme Build(bool isDark, double alpha, double backdropLuminance) + { + var surfaceBase = isDark ? DarkSurfaceColor : LightSurfaceColor; + var foreground = isDark ? Colors.White : Colors.Black; + + // 卡片底 = 半透明色"贴"在背景上;我们能知道的只有背景亮度,所以用亮度做合成, + // 不假装知道色相。这正是"只判黑白"在数学上成立的原因。 + var composited = Math.Clamp( + alpha * RelativeLuminance(surfaceBase) + (1 - alpha) * backdropLuminance, 0, 1); + + var cardAlpha = Math.Min(1.0, alpha + CardSurfaceAlphaBonus); + return new AdaptiveTheme( + IsDarkBackdrop: isDark, + Foreground: foreground, + SecondaryForeground: WithAlpha(foreground, SecondaryAlpha), + Stroke: WithAlpha(foreground, StrokeAlpha), + Surface: WithAlpha(surfaceBase, (byte)Math.Round(alpha * 255)), + CardSurface: WithAlpha(surfaceBase, (byte)Math.Round(cardAlpha * 255)), + AvatarSurface: WithAlpha(foreground, AvatarAlpha), + SurfaceLuminance: composited); + } + + private static Color WithAlpha(Color color, byte alpha) => + Color.FromArgb(alpha, color.R, color.G, color.B); + + private static double Linearize(byte channel) + { + var value = channel / 255.0; + return value <= 0.04045 ? value / 12.92 : Math.Pow((value + 0.055) / 1.055, 2.4); + } +} \ No newline at end of file diff --git a/SecRandom.Platforms.Abstractions/AGENTS.md b/SecRandom.Platforms.Abstractions/AGENTS.md index fc2d53939..a19c3c74a 100644 --- a/SecRandom.Platforms.Abstractions/AGENTS.md +++ b/SecRandom.Platforms.Abstractions/AGENTS.md @@ -12,5 +12,6 @@ This project defines app-internal, platform-neutral contracts. It is intentional - Removable-storage discovery is represented by `IRemovableStorageCatalog` and `RemovableStorageDevice`; implementations belong in each matching desktop platform project and may use that platform's native APIs or standard system commands. The catalog must return opaque stable device IDs, display names, an optional hardware/product name for user-facing selection, a user-facing display location, and current mount roots. Mount roots remain internal to the catalog/security service and must not be projected into public security models. Mobile/unsupported roots use the explicit empty catalog. - Removable-storage binding markers are represented by `IRemovableStorageBindingMarker`. Every desktop platform uses the one `.SecRandom.safety.key` file name; Windows adds hidden/system attributes while Linux/macOS use the dot-file convention. The marker contract must not expose mount roots or secret contents. - Camera discovery is represented by `IPlatformCameraDeviceCatalog` and `PlatformCameraDevice`. Matching platform projects must return actual device display names with opaque IDs, the current capture index, and an optional front/rear hint; app views must not enumerate native devices directly. Mobile heads inject their catalog into `MobilePlatformServiceRoot`; iOS uses the explicit empty catalog because the QR camera selector is hidden. +- Desktop backdrop luminance sampling is represented by `IScreenLuminanceSampler` over `ScreenLuminanceRequest` (a region in virtual-screen pixels plus optional occlusion rectangles) returning `ScreenLuminanceSample` (`P10`/`Median`/`P90` of relative luminance plus the sampled pixel count), exposed from `IPlatformServiceRoot.ScreenLuminance`. It is an on-demand single-shot probe for placing a notification window, never a capture stream: callers own the timeout, treat `null` and a small pixel count as "unknown", and must fall back to the app theme instead of inferring a backdrop. Only Windows implements it (GDI `BitBlt` into a DIB section, excluded rectangles removed per pixel); every other root returns `UnsupportedScreenLuminanceSampler.Instance`, whose `IsSupported` is false and whose `Sample` is `null`. The sample carries no colors and no image, so the contract stays free of native types. - Platform projects that invoke system discovery commands must use a bounded output reader/timeout and terminate timed-out child processes; do not call synchronous `ReadToEnd()` before waiting for process exit. - `TopmostMode.UiAccess` remains a desktop process-token startup concern and must not be represented as a generic window feature. diff --git a/SecRandom.Platforms.Abstractions/IPlatformServiceRoot.cs b/SecRandom.Platforms.Abstractions/IPlatformServiceRoot.cs index a75ff5cf9..d576cf3d0 100644 --- a/SecRandom.Platforms.Abstractions/IPlatformServiceRoot.cs +++ b/SecRandom.Platforms.Abstractions/IPlatformServiceRoot.cs @@ -14,6 +14,9 @@ public interface IPlatformServiceRoot IPlatformCameraDeviceCatalog CameraDevices { get; } + /// 屏幕亮度采样能力;只有真正实现了截屏的平台才会声明支持。 + IScreenLuminanceSampler ScreenLuminance { get; } + /// 从本机应用文件读取图标的能力。 IPlatformApplicationIconExtractor ApplicationIcons { get; } } diff --git a/SecRandom.Platforms.Abstractions/ScreenLuminance.cs b/SecRandom.Platforms.Abstractions/ScreenLuminance.cs new file mode 100644 index 000000000..cd1eeccbc --- /dev/null +++ b/SecRandom.Platforms.Abstractions/ScreenLuminance.cs @@ -0,0 +1,80 @@ +namespace SecRandom.Platforms.Abstractions; + +/// +/// 屏幕物理像素矩形。采样只在屏幕坐标里工作,所以这里刻意不使用任何 Avalonia 类型。 +/// +public readonly record struct PlatformPixelRect(int X, int Y, int Width, int Height) +{ + public static PlatformPixelRect Empty => new(0, 0, 0, 0); + + public bool IsEmpty => Width <= 0 || Height <= 0; + + public int Right => X + Width; + + public int Bottom => Y + Height; + + public bool Contains(int x, int y) => x >= X && x < Right && y >= Y && y < Bottom; + + /// 向外扩张 个像素(负数向内收缩)。 + public PlatformPixelRect Inflate(int amount) => + new(X - amount, Y - amount, Width + amount * 2, Height + amount * 2); + + public PlatformPixelRect Intersect(PlatformPixelRect other) + { + var x = Math.Max(X, other.X); + var y = Math.Max(Y, other.Y); + var right = Math.Min(Right, other.Right); + var bottom = Math.Min(Bottom, other.Bottom); + return right <= x || bottom <= y ? Empty : new PlatformPixelRect(x, y, right - x, bottom - y); + } +} + +/// +/// 一次背景采样的结果:线性相对亮度(0–1)的分位值,而不是颜色。 +/// +/// +/// 只取亮度分位是有意的:HDR、广色域、远程桌面上像素颜色都不可靠,而"这片背景是深还是浅" +/// 的结论只需要亮度。调用方据此决定前景色,不需要也不应该依赖具体色相。 +/// +public sealed record ScreenLuminanceSample(double P10, double Median, double P90, int PixelCount) +{ + public double Spread => Math.Max(0, P90 - P10); +} + +/// +/// 采样请求。 是必须先被剔除的矩形——通常是本应用自己的窗口, +/// 否则已经显示的结果卡片会把采样结果变成它自己的底色。 +/// +public sealed record ScreenLuminanceRequest( + PlatformPixelRect Region, + IReadOnlyList? Exclusions = null); + +/// +/// 读取屏幕某块区域亮度分布的能力。桌面合成、锁屏、远程桌面等场景可能失败,失败一律返回 +/// ,调用方回退到应用主题,不得把失败当成"背景是黑的"。 +/// +public interface IScreenLuminanceSampler +{ + /// 当前平台是否真的实现了采样;未实现时 只会返回 null。 + bool IsSupported { get; } + + /// + /// 同步采样(短时 CPU 密集,调用方负责放到线程池)。区域会先与虚拟屏求交,越界部分忽略。 + /// + /// 采样结果;区域为空、API 失败或安全桌面导致不可读时返回 。 + ScreenLuminanceSample? Sample(ScreenLuminanceRequest request); +} + +/// 没有屏幕采样能力的平台(Linux/macOS/移动端)使用的空实现。 +public sealed class UnsupportedScreenLuminanceSampler : IScreenLuminanceSampler +{ + public static UnsupportedScreenLuminanceSampler Instance { get; } = new(); + + private UnsupportedScreenLuminanceSampler() + { + } + + public bool IsSupported => false; + + public ScreenLuminanceSample? Sample(ScreenLuminanceRequest request) => null; +} \ No newline at end of file diff --git a/SecRandom.Platforms.Linux/LinuxPlatformServiceRoot.cs b/SecRandom.Platforms.Linux/LinuxPlatformServiceRoot.cs index 8e8e4e66b..181ee2954 100644 --- a/SecRandom.Platforms.Linux/LinuxPlatformServiceRoot.cs +++ b/SecRandom.Platforms.Linux/LinuxPlatformServiceRoot.cs @@ -34,5 +34,7 @@ public sealed class LinuxPlatformServiceRoot : IPlatformServiceRoot public IPlatformCameraDeviceCatalog CameraDevices { get; } = new LinuxCameraDeviceCatalog(); + public IScreenLuminanceSampler ScreenLuminance => UnsupportedScreenLuminanceSampler.Instance; + public IPlatformApplicationIconExtractor ApplicationIcons { get; } = new LinuxApplicationIconExtractor(); } diff --git a/SecRandom.Platforms.MacOs/MacOsPlatformServiceRoot.cs b/SecRandom.Platforms.MacOs/MacOsPlatformServiceRoot.cs index 74b4d27f2..4612e4b35 100644 --- a/SecRandom.Platforms.MacOs/MacOsPlatformServiceRoot.cs +++ b/SecRandom.Platforms.MacOs/MacOsPlatformServiceRoot.cs @@ -31,5 +31,7 @@ public sealed class MacOsPlatformServiceRoot : IPlatformServiceRoot public IPlatformCameraDeviceCatalog CameraDevices { get; } = new MacOsCameraDeviceCatalog(); + public IScreenLuminanceSampler ScreenLuminance => UnsupportedScreenLuminanceSampler.Instance; + public IPlatformApplicationIconExtractor ApplicationIcons { get; } = new MacOsApplicationIconExtractor(); } diff --git a/SecRandom.Platforms.Windows/WindowsPlatformServiceRoot.cs b/SecRandom.Platforms.Windows/WindowsPlatformServiceRoot.cs index 68cdb5a92..2cae0584d 100644 --- a/SecRandom.Platforms.Windows/WindowsPlatformServiceRoot.cs +++ b/SecRandom.Platforms.Windows/WindowsPlatformServiceRoot.cs @@ -36,5 +36,7 @@ public WindowsPlatformServiceRoot() public IPlatformCameraDeviceCatalog CameraDevices { get; } = new WindowsCameraDeviceCatalog(); + public IScreenLuminanceSampler ScreenLuminance { get; } = new WindowsScreenLuminanceSampler(); + public IPlatformApplicationIconExtractor ApplicationIcons { get; } = new WindowsApplicationIconExtractor(); } diff --git a/SecRandom.Platforms.Windows/WindowsScreenLuminanceSampler.cs b/SecRandom.Platforms.Windows/WindowsScreenLuminanceSampler.cs new file mode 100644 index 000000000..6840168ca --- /dev/null +++ b/SecRandom.Platforms.Windows/WindowsScreenLuminanceSampler.cs @@ -0,0 +1,301 @@ +using System.Runtime.InteropServices; +using SecRandom.Platforms.Abstractions; + +namespace SecRandom.Platforms.Windows; + +/// +/// Windows 上的屏幕亮度采样:一次 GDI BitBlt 抓取目标区域,再在 CPU 上做一次亮度直方图。 +/// +/// +/// +/// 只抓目标矩形(典型 300×200),不是整屏:通知卡片要知道的只是它自己脚下那块桌面。 +/// 整屏 1920×1080 是 8.3MB 的拷贝,而目标区域是几百 KB,单次耗时在毫秒级。 +/// +/// +/// 这里刻意走 GDI 而不是 Windows.Graphics.Capture:后者的帧是异步投递的(16–33ms), +/// 拿不到"窗口显示之前就已经算好"的时序;而且它需要 D3D11 环境,对一个只问黑白的小问题太重。 +/// +/// +/// 失败(安全桌面、远程会话、区域内没有任何像素)一律返回 。绝不能把 +/// "抓不到"当成"背景是黑的"——那会让锁屏后的通知强行变成白字黑底。 +/// +/// +public sealed class WindowsScreenLuminanceSampler : IScreenLuminanceSampler +{ + private const int SmXVirtualScreen = 76; + private const int SmYVirtualScreen = 77; + private const int SmCxVirtualScreen = 78; + private const int SmCyVirtualScreen = 79; + private const uint Srccopy = 0x00CC0020; + private const uint DibRgbColors = 0; + private const int BitsPerPixel = 32; + private const int HistogramSize = 1024; + private const int MaxSamples = 65536; + private const int MinimumSamples = 64; + + /// sRGB 字节到线性相对亮度的查找表:0.04045 以下走线性段,其余走 2.4 次幂。 + private static readonly double[] LinearLookup = BuildLinearLookup(); + + public bool IsSupported => OperatingSystem.IsWindows(); + + public ScreenLuminanceSample? Sample(ScreenLuminanceRequest request) + { + if (!IsSupported || request.Region.IsEmpty) + return null; + + var virtualScreen = ReadVirtualScreen(); + var region = request.Region.Intersect(virtualScreen); + if (region.IsEmpty) + return null; + + var exclusions = request.Exclusions; + if (exclusions is { Count: > 0 }) + { + // 剔除矩形后可能什么都不剩(例如窗口正好盖住整个区域),这时直接判定为不可采样。 + if (IsFullyCovered(region, exclusions)) + return null; + } + + var stride = ResolveStride(region); + var histogram = new int[HistogramSize]; + var samples = 0; + + var screenDc = GetDC(nint.Zero); + if (screenDc == nint.Zero) + return null; + + nint memoryDc = nint.Zero; + nint bitmap = nint.Zero; + try + { + memoryDc = CreateCompatibleDC(screenDc); + if (memoryDc == nint.Zero) + return null; + + var header = new BitmapInfoHeader + { + Size = (uint)Marshal.SizeOf(), + Width = region.Width, + // 负高度 = 自上而下的 DIB,省掉一次翻转的索引计算。 + Height = -region.Height, + Planes = 1, + BitCount = BitsPerPixel, + Compression = 0, + SizeImage = 0 + }; + + bitmap = CreateDIBSection(memoryDc, ref header, DibRgbColors, out var bits, nint.Zero, 0); + if (bitmap == nint.Zero || bits == nint.Zero) + return null; + + var previous = SelectObject(memoryDc, bitmap); + if (previous == nint.Zero) + return null; + + try + { + if (!BitBlt(memoryDc, 0, 0, region.Width, region.Height, screenDc, region.X, region.Y, Srccopy)) + return null; + + SamplePixels(bits, region, stride, exclusions, histogram, ref samples); + } + finally + { + SelectObject(memoryDc, previous); + } + } + catch (Exception) + { + // GDI 在会话切换时可能抛 DllNotFound/EntryPoint 等异常,采样失败不该影响通知本身。 + return null; + } + finally + { + if (bitmap != nint.Zero) + DeleteObject(bitmap); + if (memoryDc != nint.Zero) + DeleteDC(memoryDc); + ReleaseDC(nint.Zero, screenDc); + } + + if (samples < MinimumSamples) + return null; + + return new ScreenLuminanceSample( + Percentile(histogram, samples, 0.10), + Percentile(histogram, samples, 0.50), + Percentile(histogram, samples, 0.90), + samples); + } + + private static unsafe void SamplePixels( + nint bits, + PlatformPixelRect region, + int stride, + IReadOnlyList? exclusions, + int[] histogram, + ref int samples) + { + var rows = (byte*)bits; + var rowBytes = region.Width * 4; + for (var y = 0; y < region.Height; y += stride) + { + var row = rows + (long)y * rowBytes; + var screenY = region.Y + y; + for (var x = 0; x < region.Width; x += stride) + { + if (exclusions is { Count: > 0 } && IsExcluded(exclusions, region.X + x, screenY)) + continue; + + var pixel = row + x * 4; + var luminance = 0.2126 * LinearLookup[pixel[2]] + + 0.7152 * LinearLookup[pixel[1]] + + 0.0722 * LinearLookup[pixel[0]]; + var bucket = (int)(luminance * HistogramSize); + if (bucket >= HistogramSize) + bucket = HistogramSize - 1; + else if (bucket < 0) + bucket = 0; + histogram[bucket]++; + samples++; + } + } + } + + private static bool IsExcluded(IReadOnlyList exclusions, int x, int y) + { + for (var i = 0; i < exclusions.Count; i++) + { + if (exclusions[i].Contains(x, y)) + return true; + } + + return false; + } + + /// 剔除矩形是否已经把整个区域盖满。 + private static bool IsFullyCovered(PlatformPixelRect region, IReadOnlyList exclusions) + { + // 矩形数量极少(本应用自己的窗口),逐像素判定成本高于直接做覆盖格点检查,但区域很小, + // 这里用"网格抽样"近似:任何未被覆盖的格点存在就认为仍有可采样的像素。 + const int grid = 16; + for (var row = 0; row < grid; row++) + { + for (var column = 0; column < grid; column++) + { + var x = region.X + region.Width * column / grid; + var y = region.Y + region.Height * row / grid; + if (!IsExcluded(exclusions, x, y)) + return false; + } + } + + return true; + } + + private static int ResolveStride(PlatformPixelRect region) + { + var pixels = (long)region.Width * region.Height; + if (pixels <= MaxSamples) + return 1; + + var stride = (int)Math.Ceiling(Math.Sqrt(pixels / (double)MaxSamples)); + return Math.Max(1, stride); + } + + private static PlatformPixelRect ReadVirtualScreen() + { + return new PlatformPixelRect( + GetSystemMetrics(SmXVirtualScreen), + GetSystemMetrics(SmYVirtualScreen), + GetSystemMetrics(SmCxVirtualScreen), + GetSystemMetrics(SmCyVirtualScreen)); + } + + private static double Percentile(int[] histogram, int total, double percentile) + { + var target = (int)Math.Ceiling(total * percentile); + if (target < 1) + target = 1; + + var cumulative = 0; + for (var index = 0; index < histogram.Length; index++) + { + cumulative += histogram[index]; + if (cumulative >= target) + return (index + 0.5) / histogram.Length; + } + + return 1; + } + + private static double[] BuildLinearLookup() + { + var lookup = new double[256]; + for (var i = 0; i < lookup.Length; i++) + { + var value = i / 255.0; + lookup[i] = value <= 0.04045 ? value / 12.92 : Math.Pow((value + 0.055) / 1.055, 2.4); + } + + return lookup; + } + + [StructLayout(LayoutKind.Sequential)] + private struct BitmapInfoHeader + { + public uint Size; + public int Width; + public int Height; + public ushort Planes; + public ushort BitCount; + public uint Compression; + public uint SizeImage; + public int XPelsPerMeter; + public int YPelsPerMeter; + public uint ClrUsed; + public uint ClrImportant; + } + + [DllImport("user32.dll")] + private static extern nint GetDC(nint hWnd); + + [DllImport("user32.dll")] + private static extern int ReleaseDC(nint hWnd, nint hDc); + + [DllImport("user32.dll")] + private static extern int GetSystemMetrics(int nIndex); + + [DllImport("gdi32.dll")] + private static extern nint CreateCompatibleDC(nint hdc); + + [DllImport("gdi32.dll")] + private static extern bool DeleteDC(nint hdc); + + [DllImport("gdi32.dll")] + private static extern nint CreateDIBSection( + nint hdc, + ref BitmapInfoHeader pbmi, + uint usage, + out nint ppvBits, + nint hSection, + uint offset); + + [DllImport("gdi32.dll")] + private static extern nint SelectObject(nint hdc, nint h); + + [DllImport("gdi32.dll")] + private static extern bool DeleteObject(nint ho); + + [DllImport("gdi32.dll", SetLastError = true)] + private static extern bool BitBlt( + nint hdcDest, + int x, + int y, + int cx, + int cy, + nint hdcSrc, + int x1, + int y1, + uint rop); +} \ No newline at end of file diff --git a/SecRandom.Platforms/PlatformServiceRootStub.cs b/SecRandom.Platforms/PlatformServiceRootStub.cs index 6bb49d339..0502b9179 100644 --- a/SecRandom.Platforms/PlatformServiceRootStub.cs +++ b/SecRandom.Platforms/PlatformServiceRootStub.cs @@ -23,6 +23,8 @@ private PlatformServiceRootStub() public IPlatformCameraDeviceCatalog CameraDevices => UnsupportedPlatformCameraDeviceCatalog.Instance; + public IScreenLuminanceSampler ScreenLuminance => UnsupportedScreenLuminanceSampler.Instance; + public IPlatformApplicationIconExtractor ApplicationIcons => UnsupportedApplicationIconExtractor.Instance; public global::SecRandom.Platforms.Abstractions.WindowFeatures SupportedFeatures => diff --git a/SecRandom/Helpers/DrawColorHelper.cs b/SecRandom/Helpers/DrawColorHelper.cs index 96158ecdb..2b6354236 100644 --- a/SecRandom/Helpers/DrawColorHelper.cs +++ b/SecRandom/Helpers/DrawColorHelper.cs @@ -26,11 +26,16 @@ internal static class DrawColorHelper }; } - public static IBrush ResolveTextBrush(IBrush? accentBrush, ThemeMode appTheme) + public static IBrush ResolveTextBrush(IBrush? accentBrush, ThemeMode appTheme, Color? adaptiveForeground = null) { if (accentBrush is not null) return accentBrush; + // 通知卡片压在桌面上时,白/黑应该由采样到的桌面亮度决定,而不是应用主题: + // 深色主题的用户很可能正对着一页白底 PPT,反过来也一样。 + if (adaptiveForeground is { } color) + return new SolidColorBrush(color); + return IsDarkTheme(appTheme) ? Brushes.White : Brushes.Black; } diff --git a/SecRandom/Helpers/UiRenderQuality.cs b/SecRandom/Helpers/UiRenderQuality.cs index 2befde1e5..82f022502 100644 --- a/SecRandom/Helpers/UiRenderQuality.cs +++ b/SecRandom/Helpers/UiRenderQuality.cs @@ -25,7 +25,10 @@ internal static class UiRenderQuality ? BitmapInterpolationMode.LowQuality : BitmapInterpolationMode.HighQuality; - private static bool IsLowSpecMode => + /// + /// 低配模式是否开启。窗口合成、模糊与位图重采样都要读它,所以对外可见。 + /// + public static bool IsLowSpecMode => IAppHost.TryGetService()?.Data.General.PerformanceSettings.LowSpecMode == true; /// diff --git a/SecRandom/Langs/SettingsPages/Notification/Resources.Designer.cs b/SecRandom/Langs/SettingsPages/Notification/Resources.Designer.cs index 1a3d923be..89bfe6d51 100644 --- a/SecRandom/Langs/SettingsPages/Notification/Resources.Designer.cs +++ b/SecRandom/Langs/SettingsPages/Notification/Resources.Designer.cs @@ -185,120 +185,102 @@ public static string Page_Title { } } - /// - /// Looks up a localized string similar to 通知显示器. - /// - public static string S_Common_EnabledMonitor { - get { - return ResourceManager.GetString("S_Common_EnabledMonitor", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 指定通知窗口显示在哪个显示器;不指定时使用主显示器。. - /// - public static string S_Common_EnabledMonitor_D { - get { - return ResourceManager.GetString("S_Common_EnabledMonitor_D", resourceCulture); - } - } - /// /// Looks up a localized string similar to 内置通知浮窗. /// - public static string S_Common_FloatingWindow { + public static string S_FloatingWindow { get { - return ResourceManager.GetString("S_Common_FloatingWindow", resourceCulture); + return ResourceManager.GetString("S_FloatingWindow", resourceCulture); } } /// - /// Looks up a localized string similar to 浮窗关闭时间. + /// Looks up a localized string similar to 浮窗显示器. /// - public static string S_Common_FloatingWindowAutoCloseTime { + public static string S_FloatingWindow_EnabledMonitor { get { - return ResourceManager.GetString("S_Common_FloatingWindowAutoCloseTime", resourceCulture); + return ResourceManager.GetString("S_FloatingWindow_EnabledMonitor", resourceCulture); } } /// - /// Looks up a localized string similar to 内置通知浮窗自动关闭前保留的秒数。. + /// Looks up a localized string similar to 指定内置通知浮窗显示在哪个显示器;不指定时使用主显示器。. /// - public static string S_Common_FloatingWindowAutoCloseTime_D { + public static string S_FloatingWindow_EnabledMonitor_D { get { - return ResourceManager.GetString("S_Common_FloatingWindowAutoCloseTime_D", resourceCulture); + return ResourceManager.GetString("S_FloatingWindow_EnabledMonitor_D", resourceCulture); } } /// - /// Looks up a localized string similar to 浮窗显示器. + /// Looks up a localized string similar to 浮窗偏移. /// - public static string S_Common_FloatingWindowEnabledMonitor { + public static string S_FloatingWindow_Offset { get { - return ResourceManager.GetString("S_Common_FloatingWindowEnabledMonitor", resourceCulture); + return ResourceManager.GetString("S_FloatingWindow_Offset", resourceCulture); } } /// - /// Looks up a localized string similar to 指定内置通知浮窗显示在哪个显示器;不指定时使用主显示器。. + /// Looks up a localized string similar to 设置内置通知浮窗相对默认位置的水平和垂直偏移。. /// - public static string S_Common_FloatingWindowEnabledMonitor_D { + public static string S_FloatingWindow_Offset_D { get { - return ResourceManager.GetString("S_Common_FloatingWindowEnabledMonitor_D", resourceCulture); + return ResourceManager.GetString("S_FloatingWindow_Offset_D", resourceCulture); } } /// - /// Looks up a localized string similar to 浮窗偏移. + /// Looks up a localized string similar to 浮窗位置. /// - public static string S_Common_FloatingWindowOffset { + public static string S_FloatingWindow_WindowPosition { get { - return ResourceManager.GetString("S_Common_FloatingWindowOffset", resourceCulture); + return ResourceManager.GetString("S_FloatingWindow_WindowPosition", resourceCulture); } } /// - /// Looks up a localized string similar to 设置内置通知浮窗相对默认位置的水平和垂直偏移。. + /// Looks up a localized string similar to 选择内置通知浮窗的显示位置。. /// - public static string S_Common_FloatingWindowOffset_D { + public static string S_FloatingWindow_WindowPosition_D { get { - return ResourceManager.GetString("S_Common_FloatingWindowOffset_D", resourceCulture); + return ResourceManager.GetString("S_FloatingWindow_WindowPosition_D", resourceCulture); } } /// - /// Looks up a localized string similar to 浮窗位置. + /// Looks up a localized string similar to 浮窗不透明度. /// - public static string S_Common_FloatingWindowPosition { + public static string S_FloatingWindow_Transparency { get { - return ResourceManager.GetString("S_Common_FloatingWindowPosition", resourceCulture); + return ResourceManager.GetString("S_FloatingWindow_Transparency", resourceCulture); } } /// - /// Looks up a localized string similar to 选择内置通知浮窗的显示位置。. + /// Looks up a localized string similar to 设置内置通知浮窗的不透明度。. /// - public static string S_Common_FloatingWindowPosition_D { + public static string S_FloatingWindow_Transparency_D { get { - return ResourceManager.GetString("S_Common_FloatingWindowPosition_D", resourceCulture); + return ResourceManager.GetString("S_FloatingWindow_Transparency_D", resourceCulture); } } /// - /// Looks up a localized string similar to 浮窗不透明度. + /// Looks up a localized string similar to 自适应前景色. /// - public static string S_Common_FloatingWindowTransparency { + public static string S_FloatingWindow_AdaptiveForeground { get { - return ResourceManager.GetString("S_Common_FloatingWindowTransparency", resourceCulture); + return ResourceManager.GetString("S_FloatingWindow_AdaptiveForeground", resourceCulture); } } /// - /// Looks up a localized string similar to 设置内置通知浮窗的不透明度。. + /// Looks up a localized string similar to 按浮窗背后的桌面亮度自动选用白色或黑色文字与描边. /// - public static string S_Common_FloatingWindowTransparency_D { + public static string S_FloatingWindow_AdaptiveForeground_D { get { - return ResourceManager.GetString("S_Common_FloatingWindowTransparency_D", resourceCulture); + return ResourceManager.GetString("S_FloatingWindow_AdaptiveForeground_D", resourceCulture); } } @@ -338,15 +320,6 @@ public static string S_Common_BasicSettings { } } - /// - /// Looks up a localized string similar to 通知窗口. - /// - public static string S_Common_NotificationWindowSettings { - get { - return ResourceManager.GetString("S_Common_NotificationWindowSettings", resourceCulture); - } - } - /// /// Looks up a localized string similar to 启用覆盖. /// @@ -437,42 +410,6 @@ public static string S_Default_MainWindowDisplayThreshold_D { } } - /// - /// Looks up a localized string similar to 通知偏移. - /// - public static string S_Default_Offset { - get { - return ResourceManager.GetString("S_Default_Offset", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 设置通知浮窗相对默认位置的水平和垂直偏移。. - /// - public static string S_Default_Offset_D { - get { - return ResourceManager.GetString("S_Default_Offset_D", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 通知不透明度. - /// - public static string S_Default_Transparency { - get { - return ResourceManager.GetString("S_Default_Transparency", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 设置通知浮窗的不透明度。. - /// - public static string S_Default_Transparency_D { - get { - return ResourceManager.GetString("S_Default_Transparency_D", resourceCulture); - } - } - /// /// Looks up a localized string similar to 超过阈值时使用主窗口. /// @@ -491,24 +428,6 @@ public static string S_Default_UseMainWindowWhenExceedThreshold_D { } } - /// - /// Looks up a localized string similar to 通知位置. - /// - public static string S_Default_WindowPosition { - get { - return ResourceManager.GetString("S_Default_WindowPosition", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 选择通知浮窗显示位置。. - /// - public static string S_Default_WindowPosition_D { - get { - return ResourceManager.GetString("S_Default_WindowPosition_D", resourceCulture); - } - } - /// /// Looks up a localized string similar to 抽奖通知. /// @@ -590,42 +509,6 @@ public static string S_Lottery_MainWindowDisplayThreshold_D { } } - /// - /// Looks up a localized string similar to 抽奖通知偏移. - /// - public static string S_Lottery_Offset { - get { - return ResourceManager.GetString("S_Lottery_Offset", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 设置抽奖通知浮窗相对默认位置的水平和垂直偏移。. - /// - public static string S_Lottery_Offset_D { - get { - return ResourceManager.GetString("S_Lottery_Offset_D", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 抽奖通知不透明度. - /// - public static string S_Lottery_Transparency { - get { - return ResourceManager.GetString("S_Lottery_Transparency", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 设置抽奖通知浮窗的不透明度。. - /// - public static string S_Lottery_Transparency_D { - get { - return ResourceManager.GetString("S_Lottery_Transparency_D", resourceCulture); - } - } - /// /// Looks up a localized string similar to 超过阈值时使用主窗口. /// @@ -644,24 +527,6 @@ public static string S_Lottery_UseMainWindowWhenExceedThreshold_D { } } - /// - /// Looks up a localized string similar to 抽奖通知位置. - /// - public static string S_Lottery_WindowPosition { - get { - return ResourceManager.GetString("S_Lottery_WindowPosition", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 选择抽奖通知浮窗显示位置。. - /// - public static string S_Lottery_WindowPosition_D { - get { - return ResourceManager.GetString("S_Lottery_WindowPosition_D", resourceCulture); - } - } - /// /// Looks up a localized string similar to 闪抽通知. /// @@ -743,42 +608,6 @@ public static string S_QuickDraw_MainWindowDisplayThreshold_D { } } - /// - /// Looks up a localized string similar to 闪抽通知偏移. - /// - public static string S_QuickDraw_Offset { - get { - return ResourceManager.GetString("S_QuickDraw_Offset", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 设置闪抽通知浮窗相对默认位置的水平和垂直偏移。. - /// - public static string S_QuickDraw_Offset_D { - get { - return ResourceManager.GetString("S_QuickDraw_Offset_D", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 闪抽通知不透明度. - /// - public static string S_QuickDraw_Transparency { - get { - return ResourceManager.GetString("S_QuickDraw_Transparency", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 设置闪抽通知浮窗的不透明度。. - /// - public static string S_QuickDraw_Transparency_D { - get { - return ResourceManager.GetString("S_QuickDraw_Transparency_D", resourceCulture); - } - } - /// /// Looks up a localized string similar to 超过阈值时使用主窗口. /// @@ -797,24 +626,6 @@ public static string S_QuickDraw_UseMainWindowWhenExceedThreshold_D { } } - /// - /// Looks up a localized string similar to 闪抽通知位置. - /// - public static string S_QuickDraw_WindowPosition { - get { - return ResourceManager.GetString("S_QuickDraw_WindowPosition", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 选择闪抽通知浮窗显示位置。. - /// - public static string S_QuickDraw_WindowPosition_D { - get { - return ResourceManager.GetString("S_QuickDraw_WindowPosition_D", resourceCulture); - } - } - /// /// Looks up a localized string similar to 点名通知. /// @@ -896,42 +707,6 @@ public static string S_RollCall_MainWindowDisplayThreshold_D { } } - /// - /// Looks up a localized string similar to 点名通知偏移. - /// - public static string S_RollCall_Offset { - get { - return ResourceManager.GetString("S_RollCall_Offset", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 设置点名通知浮窗相对默认位置的水平和垂直偏移。. - /// - public static string S_RollCall_Offset_D { - get { - return ResourceManager.GetString("S_RollCall_Offset_D", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 点名通知不透明度. - /// - public static string S_RollCall_Transparency { - get { - return ResourceManager.GetString("S_RollCall_Transparency", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 设置点名通知浮窗的不透明度。. - /// - public static string S_RollCall_Transparency_D { - get { - return ResourceManager.GetString("S_RollCall_Transparency_D", resourceCulture); - } - } - /// /// Looks up a localized string similar to 超过阈值时使用主窗口. /// @@ -951,28 +726,20 @@ public static string S_RollCall_UseMainWindowWhenExceedThreshold_D { } /// - /// Looks up a localized string similar to 点名通知位置. + /// Looks up a localized string similar to 全屏通知. /// - public static string S_RollCall_WindowPosition { + public static string Page_Fullscreen { get { - return ResourceManager.GetString("S_RollCall_WindowPosition", resourceCulture); + return ResourceManager.GetString("Page_Fullscreen", resourceCulture); } } /// - /// Looks up a localized string similar to 选择点名通知浮窗显示位置。. - /// - public static string S_RollCall_WindowPosition_D { - get { - return ResourceManager.GetString("S_RollCall_WindowPosition_D", resourceCulture); - } - } - /// - /// Looks up a localized string similar to 全屏通知. + /// Looks up a localized string similar to 内置通知浮窗. /// - public static string Page_Fullscreen { + public static string Page_FloatingWindow { get { - return ResourceManager.GetString("Page_Fullscreen", resourceCulture); + return ResourceManager.GetString("Page_FloatingWindow", resourceCulture); } } diff --git a/SecRandom/Langs/SettingsPages/Notification/Resources.en-US.resx b/SecRandom/Langs/SettingsPages/Notification/Resources.en-US.resx index bdbd170fc..2337f9833 100644 --- a/SecRandom/Langs/SettingsPages/Notification/Resources.en-US.resx +++ b/SecRandom/Langs/SettingsPages/Notification/Resources.en-US.resx @@ -2,10 +2,9 @@ text/microsoft-resx1.3System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - Default Notification SettingsDefault Reminder SettingsEnable NotificationsShow notification results after a drawNotification AnimationPlay enter and exit animations when showing notificationsNotification PositionChoose where the notification window is displayedNotification OffsetSet the horizontal and vertical offset from the default notification positionNotification OpacitySet the opacity of the notification windowNotification Display DurationNumber of seconds the notification service displays resultsUse Main Window Above ThresholdWhen the draw count exceeds the threshold, show results only in the main windowNotification ThresholdUse the main window to show results above this count + Default Notification SettingsDefault Reminder SettingsEnable NotificationsShow notification results after a drawNotification AnimationPlay enter and exit animations when showing notificationsNotification Display DurationNumber of seconds the notification service displays resultsUse Main Window Above ThresholdWhen the draw count exceeds the threshold, show results only in the main windowNotification ThresholdUse the main window to show results above this count Roll-call NotificationsEnable Roll-call NotificationsShow notification results after roll-callRoll-call Notification AnimationPlay enter and exit animations when showing notificationsQuick Draw NotificationsEnable Quick Draw NotificationsShow notification results after Quick DrawLottery NotificationsEnable Lottery NotificationsShow notification results after the lottery - When the number of students exceeds the threshold, show results only in the main windowWhen the number of prizes exceeds the threshold, show results only in the main windowRoll-call Notification OffsetSet the opacity of the roll-call notification windowLottery Notification PositionSet the opacity of the Quick Draw notification windowUse the main window to show results above this number of peoplePlay enter and exit animations when showing lottery notificationsLottery Notification ThresholdRoll-call Notification OpacityQuick Draw Notification OffsetLottery Notification OffsetRoll-call Notification ThresholdLeftSet the horizontal and vertical offset from the default Quick Draw notification positionNumber of seconds the notification service displays Quick Draw resultsUse Main Window Above ThresholdLottery Notification OpacityRightQuick Draw Notification AnimationQuick Draw Notification Display DurationUse the main window to show results above this number of peopleWhen the number of people exceeds the threshold, show results only in the main windowChoose where the Quick Draw notification window is displayedQuick Draw Notification PositionLottery Notification AnimationSet the horizontal and vertical offset from the default roll-call notification positionUse Main Window Above ThresholdUse the main window to show results above this number of prizesTopQuick Draw Notification OpacityCenterRoll-call Notification PositionLottery Notification Display DurationQuick Draw Notification ThresholdBottomUse Main Window Above ThresholdPlay enter and exit animations when showing Quick Draw notificationsChoose where the lottery notification window is displayedSet the horizontal and vertical offset from the default lottery notification positionNumber of seconds the notification service displays roll-call resultsNumber of seconds the notification service displays lottery resultsChoose where the roll-call notification window is displayedRoll-call Notification Display DurationSet the opacity of the lottery notification window - Top LeftTop RightBottom LeftBottom RightSecRandom Floating NotificationsClassIslandUse both (ClassIsland + floating notifications)Notification MonitorChoose the monitor for the notification window; the primary monitor is used when unspecifiedBuilt-in Notification WindowFloating Window MonitorChoose the monitor for the built-in notification window; the primary monitor is used when unspecifiedFloating Window PositionChoose where the built-in notification window is displayedFloating Window OffsetSet the horizontal and vertical offset from the default built-in notification positionFloating Window OpacitySet the opacity of the built-in notification windowFloating Window Close TimeSeconds the built-in notification window remains before closing automaticallyNotification ServiceNotification Service TypeChoose how draw results are presentedFall back to floating notifications on service failureUse SecRandom floating notifications when the selected external service cannot deliverBasic SettingsOverridable SettingsNotification WindowEnable OverrideNot specified{0}: {1}x{2} @ {3},{4}{5} (Primary) + When the number of students exceeds the threshold, show results only in the main windowWhen the number of prizes exceeds the threshold, show results only in the main windowUse the main window to show results above this number of peoplePlay enter and exit animations when showing lottery notificationsLottery Notification ThresholdRoll-call Notification ThresholdLeftNumber of seconds the notification service displays Quick Draw resultsUse Main Window Above ThresholdRightQuick Draw Notification AnimationQuick Draw Notification Display DurationUse the main window to show results above this number of peopleWhen the number of people exceeds the threshold, show results only in the main windowLottery Notification AnimationUse Main Window Above ThresholdUse the main window to show results above this number of prizesTopCenterLottery Notification Display DurationQuick Draw Notification ThresholdBottomUse Main Window Above ThresholdPlay enter and exit animations when showing Quick Draw notificationsNumber of seconds the notification service displays roll-call resultsNumber of seconds the notification service displays lottery resultsRoll-call Notification Display Duration Top LeftTop RightBottom LeftBottom RightSecRandom Floating NotificationsClassIslandUse both (ClassIsland + floating notifications)Built-in Notification WindowFloating Window MonitorChoose the monitor for the built-in notification window; the primary monitor is used when unspecifiedFloating Window PositionChoose where the built-in notification window is displayedFloating Window OffsetSet the horizontal and vertical offset from the default built-in notification positionFloating Window OpacitySet the opacity of the built-in notification windowNotification ServiceNotification Service TypeChoose how draw results are presentedFall back to floating notifications on service failureUse SecRandom floating notifications when the selected external service cannot deliverBasic SettingsOverridable SettingsEnable OverrideNot specified{0}: {1}x{2} @ {3},{4}{5} (Primary) Fullscreen notification Fullscreen notification Present draw results on a full screen with background, animation and auto close @@ -84,4 +83,9 @@ {0} chars/sec Accent color mode Follow the theme color, or pick a custom color after choosing the custom option + + Built-in Notification Floating Window + + Adaptive Foreground Color + Picks white or black text and outlines from the desktop brightness behind the window so the result card stays readable on any wallpaper; low-spec mode turns this off diff --git a/SecRandom/Langs/SettingsPages/Notification/Resources.ja-JP.resx b/SecRandom/Langs/SettingsPages/Notification/Resources.ja-JP.resx index 94601bc12..fa1c6945a 100644 --- a/SecRandom/Langs/SettingsPages/Notification/Resources.ja-JP.resx +++ b/SecRandom/Langs/SettingsPages/Notification/Resources.ja-JP.resx @@ -2,10 +2,9 @@ text/microsoft-resx1.3System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - 既定の通知設定既定の通知設定通知を有効化抽選後に通知結果を表示します通知アニメーション通知の表示時に開始・終了アニメーションを再生します通知位置通知ウィンドウの表示位置を選択します通知のオフセット既定の通知位置からの水平・垂直オフセットを設定します通知の不透明度通知ウィンドウの不透明度を設定します通知の表示時間通知サービスが結果を表示する秒数を設定しますしきい値超過時はメインウィンドウを使用抽選数がしきい値を超えた場合、通知を表示せずメインウィンドウだけに結果を表示します通知のしきい値この数を超えた場合はメインウィンドウに結果を表示します + 既定の通知設定既定の通知設定通知を有効化抽選後に通知結果を表示します通知アニメーション通知の表示時に開始・終了アニメーションを再生します通知の表示時間通知サービスが結果を表示する秒数を設定しますしきい値超過時はメインウィンドウを使用抽選数がしきい値を超えた場合、通知を表示せずメインウィンドウだけに結果を表示します通知のしきい値この数を超えた場合はメインウィンドウに結果を表示します 点呼通知点呼通知を有効化点呼後に通知結果を表示します点呼通知アニメーション通知の表示時に開始・終了アニメーションを再生しますクイック抽選通知クイック抽選通知を有効化クイック抽選後に通知結果を表示しますくじ引き通知くじ引き通知を有効化くじ引き後に通知結果を表示します - 人数がしきい値を超えた場合、通知を表示せずメインウィンドウだけに結果を表示します景品数がしきい値を超えた場合、通知を表示せずメインウィンドウだけに結果を表示します点呼通知のオフセット点呼通知ウィンドウの不透明度を設定しますくじ引き通知の位置クイック抽選通知ウィンドウの不透明度を設定しますこの人数を超えた場合はメインウィンドウに結果を表示しますくじ引き通知の表示時に開始・終了アニメーションを再生しますくじ引き通知のしきい値点呼通知の不透明度クイック抽選通知のオフセットくじ引き通知のオフセット点呼通知のしきい値左既定のクイック抽選通知位置からの水平・垂直オフセットを設定します通知サービスがクイック抽選結果を表示する秒数を設定しますしきい値超過時はメインウィンドウを使用くじ引き通知の不透明度右クイック抽選通知アニメーションクイック抽選通知の表示時間この人数を超えた場合はメインウィンドウに結果を表示します人数がしきい値を超えた場合、通知を表示せずメインウィンドウだけに結果を表示しますクイック抽選通知ウィンドウの表示位置を選択しますクイック抽選通知の位置くじ引き通知アニメーション既定の点呼通知位置からの水平・垂直オフセットを設定しますしきい値超過時はメインウィンドウを使用この景品数を超えた場合はメインウィンドウに結果を表示します上クイック抽選通知の不透明度中央点呼通知の位置くじ引き通知の表示時間クイック抽選通知のしきい値下しきい値超過時はメインウィンドウを使用クイック抽選通知の表示時に開始・終了アニメーションを再生しますくじ引き通知ウィンドウの表示位置を選択します既定のくじ引き通知位置からの水平・垂直オフセットを設定します通知サービスが点呼結果を表示する秒数を設定します通知サービスがくじ引き結果を表示する秒数を設定します点呼通知ウィンドウの表示位置を選択します点呼通知の表示時間くじ引き通知ウィンドウの不透明度を設定します - 左上右上左下右下SecRandom フローティング通知ClassIsland両方を使用(ClassIsland + フローティング通知)通知モニター通知ウィンドウを表示するモニターを指定し、未指定時はメインモニターを使用します内蔵通知フローティングウィンドウフローティングウィンドウのモニター内蔵通知ウィンドウを表示するモニターを指定し、未指定時はメインモニターを使用しますフローティングウィンドウの位置内蔵通知ウィンドウの表示位置を選択しますフローティングウィンドウのオフセット既定の内蔵通知位置からの水平・垂直オフセットを設定しますフローティングウィンドウの不透明度内蔵通知ウィンドウの不透明度を設定しますフローティングウィンドウの終了時間内蔵通知ウィンドウが自動終了するまでの秒数通知サービス通知サービスの種類抽選結果の表示方法を選択しますサービス失敗時にフローティング通知へフォールバック選択した外部サービスが配信できない場合、SecRandom フローティング通知を使用します基本設定上書き可能な設定通知ウィンドウ上書きを有効化指定しない{0}: {1}x{2} @ {3},{4}{5} (メインディスプレイ) + 人数がしきい値を超えた場合、通知を表示せずメインウィンドウだけに結果を表示します景品数がしきい値を超えた場合、通知を表示せずメインウィンドウだけに結果を表示しますこの人数を超えた場合はメインウィンドウに結果を表示しますくじ引き通知の表示時に開始・終了アニメーションを再生しますくじ引き通知のしきい値点呼通知のしきい値左通知サービスがクイック抽選結果を表示する秒数を設定しますしきい値超過時はメインウィンドウを使用右クイック抽選通知アニメーションクイック抽選通知の表示時間この人数を超えた場合はメインウィンドウに結果を表示します人数がしきい値を超えた場合、通知を表示せずメインウィンドウだけに結果を表示しますくじ引き通知アニメーションしきい値超過時はメインウィンドウを使用この景品数を超えた場合はメインウィンドウに結果を表示します上中央くじ引き通知の表示時間クイック抽選通知のしきい値下しきい値超過時はメインウィンドウを使用クイック抽選通知の表示時に開始・終了アニメーションを再生します通知サービスが点呼結果を表示する秒数を設定します通知サービスがくじ引き結果を表示する秒数を設定します点呼通知の表示時間 左上右上左下右下SecRandom フローティング通知ClassIsland両方を使用(ClassIsland + フローティング通知)内蔵通知フローティングウィンドウフローティングウィンドウのモニター内蔵通知ウィンドウを表示するモニターを指定し、未指定時はメインモニターを使用しますフローティングウィンドウの位置内蔵通知ウィンドウの表示位置を選択しますフローティングウィンドウのオフセット既定の内蔵通知位置からの水平・垂直オフセットを設定しますフローティングウィンドウの不透明度内蔵通知ウィンドウの不透明度を設定します通知サービス通知サービスの種類抽選結果の表示方法を選択しますサービス失敗時にフローティング通知へフォールバック選択した外部サービスが配信できない場合、SecRandom フローティング通知を使用します基本設定上書き可能な設定上書きを有効化指定しない{0}: {1}x{2} @ {3},{4}{5} (メインディスプレイ) 全画面通知 全画面通知 抽選結果を全画面で表示します。背景・アニメーション・自動終了を含みます @@ -84,4 +83,9 @@ {0} 文字/秒 アクセントカラーのモード テーマ色に従うか、カスタム色を選んで自分で色を指定します + + 内蔵通知フローティングウィンドウ + + 前景色の自動調整 + ウィンドウ背後のデスクトップの明るさから白または黒の文字と枠線を選び、どの壁紙でも結果カードを読みやすくします。低スペックモードでは強制的に無効になります diff --git a/SecRandom/Langs/SettingsPages/Notification/Resources.resx b/SecRandom/Langs/SettingsPages/Notification/Resources.resx index 42eb9708c..5fec06a20 100644 --- a/SecRandom/Langs/SettingsPages/Notification/Resources.resx +++ b/SecRandom/Langs/SettingsPages/Notification/Resources.resx @@ -33,24 +33,6 @@ 显示通知时播放进入和退出动画 - - 通知位置 - - - 选择通知浮窗显示位置 - - - 通知偏移 - - - 设置通知浮窗相对默认位置的水平和垂直偏移 - - - 通知不透明度 - - - 设置通知浮窗的不透明度 - 通知显示时长 @@ -108,18 +90,6 @@ 抽取奖品数超过阈值时不显示浮窗通知,仅在主窗口显示结果 - - 点名通知偏移 - - - 设置点名通知浮窗的不透明度 - - - 抽奖通知位置 - - - 设置闪抽通知浮窗的不透明度 - 超过此人数后使用主窗口显示结果 @@ -129,33 +99,18 @@ 抽奖通知阈值 - - 点名通知不透明度 - - - 闪抽通知偏移 - - - 抽奖通知偏移 - 点名通知阈值 左侧 - - 设置闪抽通知浮窗相对默认位置的水平和垂直偏移 - 设置通知服务显示闪抽结果的秒数 超过阈值时使用主窗口 - - 抽奖通知不透明度 - 右侧 @@ -171,18 +126,9 @@ 抽取人数超过阈值时不显示浮窗通知,仅在主窗口显示结果 - - 选择闪抽通知浮窗显示位置 - - - 闪抽通知位置 - 抽奖通知动画 - - 设置点名通知浮窗相对默认位置的水平和垂直偏移 - 超过阈值时使用主窗口 @@ -192,15 +138,9 @@ 顶部 - - 闪抽通知不透明度 - 中心 - - 点名通知位置 - 抽奖通知显示时长 @@ -216,27 +156,15 @@ 显示闪抽通知时播放进入和退出动画 - - 选择抽奖通知浮窗显示位置 - - - 设置抽奖通知浮窗相对默认位置的水平和垂直偏移 - 设置通知服务显示点名结果的秒数 设置通知服务显示抽奖结果的秒数 - - 选择点名通知浮窗显示位置 - 点名通知显示时长 - - 设置抽奖通知浮窗的不透明度 - 左上 @@ -258,45 +186,33 @@ 同时使用(ClassIsland + 浮窗通知) - - 通知显示器 - - - 指定通知窗口显示在哪个显示器;不指定时使用主显示器 - - + 内置通知浮窗 - + 浮窗显示器 - + 指定内置通知浮窗显示在哪个显示器;不指定时使用主显示器 - + 浮窗位置 - + 选择内置通知浮窗的显示位置 - + 浮窗偏移 - + 设置内置通知浮窗相对默认位置的水平和垂直偏移 - + 浮窗不透明度 - + 设置内置通知浮窗的不透明度 - - 浮窗关闭时间 - - - 内置通知浮窗自动关闭前保留的秒数 - 通知服务 @@ -318,9 +234,6 @@ 可覆盖设置 - - 通知窗口 - 启用覆盖 @@ -567,4 +480,13 @@ 跟随主题色,或选择自定义颜色后自行取色 + + 内置通知浮窗 + + + 自适应前景色 + + + 按浮窗背后的桌面亮度自动选用白色或黑色文字与描边,让结果卡片在任何壁纸上都清晰可读;低配模式下此项会被强制关闭 + diff --git a/SecRandom/ViewModels/MainPages/QuickDrawPageViewModel.cs b/SecRandom/ViewModels/MainPages/QuickDrawPageViewModel.cs index 1ebd88f66..8f060f32b 100644 --- a/SecRandom/ViewModels/MainPages/QuickDrawPageViewModel.cs +++ b/SecRandom/ViewModels/MainPages/QuickDrawPageViewModel.cs @@ -22,6 +22,7 @@ using SecRandom.Core.Services.Config; using SecRandom.Core.Services.ControlNode; using SecRandom.Core.Services.Draw; +using SecRandom.Core.Services.Presentation; using SecRandom.Core.Services.Profiles; using SecRandom.Helpers; using QuickDrawResources = SecRandom.Langs.MainPages.QuickDraw.Resources; @@ -730,9 +731,21 @@ public void ShowNotificationPreview( [ObservableProperty] private double? _notificationOpacity; + /// + /// 本次通知的自适应配色。由 App 在窗口显示前按桌面亮度算好, + /// 页面据此换掉 Fluent 画笔;为 null 时沿用应用主题。 + /// + [ObservableProperty] private AdaptiveTheme? _notificationTheme; + + public void ApplyNotificationTheme(AdaptiveTheme? theme) + { + NotificationTheme = theme; + } + public void ClearNotificationPresentation() { NotificationOpacity = null; + NotificationTheme = null; } public void ResetForCourseLinkage() @@ -759,6 +772,11 @@ private QuickDrawResultItem CreateResultItem(Student student) { var weight = BuildDisplayWeight(student); var accentBrush = ResolveAccentBrush(); + // 通知卡片压在桌面(用户自己的壁纸/PPT)上,强调色在这里只留给边框: + // 文字如果继续用强调色,浅色桌面上一个亮黄/亮青的强调色会直接消失。 + var textBrush = NotificationTheme is { } theme + ? DrawColorHelper.ResolveTextBrush(null, Config.Appearance.Theme, theme.Foreground) + : DrawColorHelper.ResolveTextBrush(accentBrush, Config.Appearance.Theme); return new QuickDrawResultItem( FormatStudent(student), student.Tags, @@ -779,13 +797,18 @@ private QuickDrawResultItem CreateResultItem(Student student) private QuickDrawResultItem CreateNotificationResultItem(string item) { var accentBrush = ResolveAccentBrush(); + // 通知卡片压在桌面(用户自己的壁纸/PPT)上,强调色在这里只留给边框: + // 文字如果继续用强调色,浅色桌面上一个亮黄/亮青的强调色会直接消失。 + var textBrush = NotificationTheme is { } theme + ? DrawColorHelper.ResolveTextBrush(null, Config.Appearance.Theme, theme.Foreground) + : DrawColorHelper.ResolveTextBrush(accentBrush, Config.Appearance.Theme); return new QuickDrawResultItem( item, string.Empty, false, DisplaySettings.DisplayStyle == DisplayStyleMode.Card, accentBrush, - DrawColorHelper.ResolveTextBrush(accentBrush, Config.Appearance.Theme), + textBrush, false, string.Empty, 1, diff --git a/SecRandom/Views/MainPages/QuickDrawPage.axaml.cs b/SecRandom/Views/MainPages/QuickDrawPage.axaml.cs index 27bb9a0a5..1f31098dc 100644 --- a/SecRandom/Views/MainPages/QuickDrawPage.axaml.cs +++ b/SecRandom/Views/MainPages/QuickDrawPage.axaml.cs @@ -1,4 +1,5 @@ using System; +using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using System.ComponentModel; @@ -6,11 +7,13 @@ using Avalonia.Controls; using Avalonia.Input; using Avalonia.Interactivity; +using Avalonia.Media; using Avalonia.Threading; using SecRandom.Core.Abstraction; using SecRandom.Core.Behaviors; using SecRandom.Core.Abstraction.Services.Presentation; using SecRandom.Core.Models.SubConfigs; +using SecRandom.Core.Services.Presentation; using SecRandom.Helpers; using SecRandom.ViewModels.MainPages; using CommonResources = SecRandom.Langs.Common.Resources; @@ -30,6 +33,9 @@ public partial class QuickDrawPage : UserControl private int _clickCount; private int _remainingAutoCloseSeconds; + /// 本次自动关闭是否走四周描边;描边创建失败时回退到原有的文字倒计时。 + private bool _usesEdgeCountdown; + public QuickDrawPage() { ViewModel = IAppHost.GetService(); @@ -39,6 +45,7 @@ public QuickDrawPage() ViewModel.PropertyChanged += ViewModel_OnPropertyChanged; ViewModel.Config.EffectiveFloatingWindowSettings.PropertyChanged += FloatingWindowSettings_OnPropertyChanged; UpdateFloatingWindowOpacity(); + ApplyNotificationTheme(ViewModel.NotificationTheme); Unloaded += OnUnloaded; } @@ -79,6 +86,37 @@ private void UpdateFloatingWindowOpacity() 100) / 100.0; } + /// + /// 把通知窗口的 Fluent 画笔替换成按桌面亮度算出的自适应配色;null 表示恢复应用主题。 + /// + /// + /// 写入的是 自己的资源字典。DynamicResource 从控件自身开始向上查找, + /// 所以卡片里所有模板(结果项、头像占位、状态文字)会一起换色,而页面上层 + /// QuickDrawAvatarTemplate 之类的模板资源不受影响;传 null 时清空该字典即可落回主题。 + /// + public void ApplyNotificationTheme(AdaptiveTheme? theme) + { + if (RootBorder is null) + return; + + if (theme is not { } adaptive) + { + RootBorder.Resources = new ResourceDictionary(); + return; + } + + RootBorder.Resources = new ResourceDictionary + { + ["SolidBackgroundFillColorBaseBrush"] = new SolidColorBrush(adaptive.Surface), + ["ControlElevationBorderBrush"] = new SolidColorBrush(adaptive.Stroke), + ["TextFillColorPrimaryBrush"] = new SolidColorBrush(adaptive.Foreground), + ["TextFillColorSecondaryBrush"] = new SolidColorBrush(adaptive.SecondaryForeground), + ["TextFillColorTertiaryBrush"] = new SolidColorBrush(adaptive.SecondaryForeground), + ["CardBackgroundFillColorDefaultBrush"] = new SolidColorBrush(adaptive.CardSurface), + ["ControlFillColorSecondaryBrush"] = new SolidColorBrush(adaptive.AvatarSurface) + }; + } + private void RootBorder_OnPointerPressed(object? sender, PointerPressedEventArgs e) { if (!App.SupportsProgrammaticWindowPositioning) @@ -136,6 +174,9 @@ private void ViewModel_OnPropertyChanged(object? sender, PropertyChangedEventArg if (e.PropertyName == nameof(QuickDrawPageViewModel.NotificationOpacity)) UpdateFloatingWindowOpacity(); + if (e.PropertyName == nameof(QuickDrawPageViewModel.NotificationTheme)) + ApplyNotificationTheme(ViewModel.NotificationTheme); + Dispatcher.UIThread.Post(async () => await RunResultAnimationAsync(e.PropertyName), DispatcherPriority.Render); } @@ -242,19 +283,40 @@ private async Task CloseAfterDelayAsync(int autoCloseRevision) { var seconds = ViewModel.ResultAutoCloseTime; _remainingAutoCloseSeconds = seconds; + _usesEdgeCountdown = seconds > 0 && TryApplyEdgeCountdownAppearance(); UpdateAutoCloseHint(); if (seconds == 0) return; var cts = new CancellationTokenSource(); _autoCloseCts = cts; + var total = TimeSpan.FromSeconds(seconds); + var stopwatch = Stopwatch.StartNew(); try { - while (_remainingAutoCloseSeconds > 0) + if (_usesEdgeCountdown) { - await Task.Delay(TimeSpan.FromSeconds(1), cts.Token); - _remainingAutoCloseSeconds--; - UpdateAutoCloseHint(); + // 描边按真实剩余时间逐帧收缩,而不是每秒跳一格:窗口缩小时也不会突然加快。 + while (true) + { + var remaining = total - stopwatch.Elapsed; + if (remaining <= TimeSpan.Zero) + break; + + CountdownRing.Progress = remaining / total; + await Task.Delay(AnimationFramePolicy.FrameIntervalMs, cts.Token); + } + + _remainingAutoCloseSeconds = 0; + } + else + { + while (_remainingAutoCloseSeconds > 0) + { + await Task.Delay(TimeSpan.FromSeconds(1), cts.Token); + _remainingAutoCloseSeconds--; + UpdateAutoCloseHint(); + } } if (!_isUnloaded && autoCloseRevision == _autoCloseRevision && ReferenceEquals(_autoCloseCts, cts)) @@ -265,8 +327,13 @@ private async Task CloseAfterDelayAsync(int autoCloseRevision) } finally { + // 只有仍然是「当前这次自动关闭」时才收掉描边:更晚的一次已经接管时不能把它的描边藏掉。 if (ReferenceEquals(_autoCloseCts, cts)) + { _autoCloseCts = null; + HideCountdownRing(); + } + cts.Dispose(); } } @@ -276,11 +343,51 @@ private void CancelAutoClose() _autoCloseCts?.Cancel(); _autoCloseCts = null; _remainingAutoCloseSeconds = 0; + _usesEdgeCountdown = false; + HideCountdownRing(); UpdateAutoCloseHint(); } + /// 按配置决定这次自动关闭画不画四周描边;任何失败都退回文字倒计时。 + private bool TryApplyEdgeCountdownAppearance() + { + try + { + var settings = ViewModel.Config.NotificationSettings.Default; + if (!settings.UsesEdgeCountdown) + return false; + + CountdownRing.SetPalette( + settings.CountdownColorMode == (int)NotificationCountdownColorMode.Gradient, + settings.ResolvedCountdownColors); + CountdownRing.Progress = 1; + CountdownRing.IsVisible = true; + return true; + } + catch + { + HideCountdownRing(); + return false; + } + } + + private void HideCountdownRing() + { + CountdownRing.IsVisible = false; + CountdownRing.Progress = 1; + } + private void UpdateAutoCloseHint() { + // 描边已经在表达剩余时间,这一行只留「三连击关闭」的静态说明,避免两个倒计时同时读秒。 + if (_usesEdgeCountdown && _remainingAutoCloseSeconds > 0) + { + AutoCloseHintTextBlock.Text = + CommonResources.ResourceManager.GetString("C_QuickDrawManualCloseHint", CommonResources.Culture) + ?? throw new InvalidOperationException("Quick draw manual-close localization is missing."); + return; + } + AutoCloseHintTextBlock.Text = _remainingAutoCloseSeconds > 0 ? string.Format( CommonResources.ResourceManager.GetString("C_QuickDrawAutoCloseHint", CommonResources.Culture) diff --git a/SecRandom/Views/SettingsPages/Notification/DefaultNotificationSettingsPage.axaml b/SecRandom/Views/SettingsPages/Notification/DefaultNotificationSettingsPage.axaml index fff93c0d1..d6eb933e5 100644 --- a/SecRandom/Views/SettingsPages/Notification/DefaultNotificationSettingsPage.axaml +++ b/SecRandom/Views/SettingsPages/Notification/DefaultNotificationSettingsPage.axaml @@ -8,69 +8,6 @@ x:DataType="notification:DefaultNotificationSettingsPage"> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Text(nameof(EnabledDescription), "S_Default_Enabled_D"); public override string AnimationTitle => Text(nameof(AnimationTitle), "S_Default_Animation"); public override string AnimationDescription => Text(nameof(AnimationDescription), "S_Default_Animation_D"); - public override string WindowPositionTitle => Text(nameof(WindowPositionTitle), "S_Default_WindowPosition"); - public override string WindowPositionDescription => Text(nameof(WindowPositionDescription), "S_Default_WindowPosition_D"); - public override string OffsetTitle => Text(nameof(OffsetTitle), "S_Default_Offset"); - public override string OffsetDescription => Text(nameof(OffsetDescription), "S_Default_Offset_D"); - public override string TransparencyTitle => Text(nameof(TransparencyTitle), "S_Default_Transparency"); - public override string TransparencyDescription => Text(nameof(TransparencyDescription), "S_Default_Transparency_D"); public override string DisplayDurationTitle => Text(nameof(DisplayDurationTitle), "S_Default_DisplayDuration"); public override string DisplayDurationDescription => Text(nameof(DisplayDurationDescription), "S_Default_DisplayDuration_D"); public override string UseMainWindowWhenExceedThresholdTitle => Text(nameof(UseMainWindowWhenExceedThresholdTitle), "S_Default_UseMainWindowWhenExceedThreshold"); diff --git a/SecRandom/Views/SettingsPages/Notification/FullscreenNotificationSettingsPage.axaml b/SecRandom/Views/SettingsPages/Notification/FullscreenNotificationSettingsPage.axaml index 317537ed1..b3b18309a 100644 --- a/SecRandom/Views/SettingsPages/Notification/FullscreenNotificationSettingsPage.axaml +++ b/SecRandom/Views/SettingsPages/Notification/FullscreenNotificationSettingsPage.axaml @@ -104,11 +104,12 @@ Description="{x:Static lsp:Resources.S_Fullscreen_BackgroundBlur_D}" IconSource="{sr:FluentIconSource {sr:Fi BlurFilled}}"> - + + Value="{Binding BackgroundBlurRadius, Mode=TwoWay}" /> + Text="{Binding BackgroundBlurRadius}" /> @@ -222,6 +223,7 @@ diff --git a/SecRandom/Views/SettingsPages/Notification/FullscreenNotificationSettingsPage.axaml.cs b/SecRandom/Views/SettingsPages/Notification/FullscreenNotificationSettingsPage.axaml.cs index dd4fda994..2674c6392 100644 --- a/SecRandom/Views/SettingsPages/Notification/FullscreenNotificationSettingsPage.axaml.cs +++ b/SecRandom/Views/SettingsPages/Notification/FullscreenNotificationSettingsPage.axaml.cs @@ -84,8 +84,30 @@ public FullscreenNotificationSettingsPage() public IReadOnlyList AccentColorModeOptions { get; private set; } + /// + /// 低配模式会把全屏通知压成"直接展示结果"并跳过背景模糊(见 FullscreenNotificationPresenter.ResolveStyle + /// 与 FullscreenNotificationWindow 的模糊分支),这两个控件此时已无意义,统一置灰并显示实际生效值。 + /// + public bool IsLowSpecModeActive => UiRenderQuality.IsLowSpecMode; + /// 文案分区(含打字机速度)只在打字机样式下有意义,其余样式直接展示结果画面。 - public bool IsTypewriterStyle => Settings.AnimationStyle == FullscreenAnimationStyle.Typewriter; + public bool IsTypewriterStyle => !IsLowSpecModeActive && Settings.AnimationStyle == FullscreenAnimationStyle.Typewriter; + + /// + /// 背景模糊的可写视图:低配模式不渲染模糊,因此对外显示 0 并拒绝写入, + /// 用户原来的半径留在配置里,退出低配后自动恢复。 + /// + public int BackgroundBlurRadius + { + get => IsLowSpecModeActive ? 0 : Settings.BackgroundBlurRadius; + set + { + if (IsLowSpecModeActive || Settings.BackgroundBlurRadius == value) + return; + + Settings.BackgroundBlurRadius = value; + } + } /// 背景图导入、模糊与背景不透明度只在自定义图片模式下出现。 public bool IsBackgroundImageMode => Settings.BackgroundMode == FullscreenBackgroundMode.Image; @@ -114,11 +136,16 @@ public FullscreenNotificationSettingsPage() public AnimationStyleOption SelectedAnimationStyleOption { - get => AnimationStyleOptions.FirstOrDefault(option => option.Value == Settings.AnimationStyle) - ?? AnimationStyleOptions[0]; + get + { + // 低配模式固定按 Direct 播放,选中项也显示为 Direct,避免"选了打字机却不生效"。 + var style = IsLowSpecModeActive ? FullscreenAnimationStyle.Direct : Settings.AnimationStyle; + return AnimationStyleOptions.FirstOrDefault(option => option.Value == style) + ?? AnimationStyleOptions[0]; + } set { - if (value is null || Settings.AnimationStyle == value.Value) + if (IsLowSpecModeActive || value is null || Settings.AnimationStyle == value.Value) return; Settings.AnimationStyle = value.Value; @@ -274,6 +301,9 @@ private void OnPageLoaded(object? sender, RoutedEventArgs e) private void NotifyDerivedSettingsProperties() { OnPropertyChanged(nameof(IsTypewriterStyle)); + OnPropertyChanged(nameof(IsLowSpecModeActive)); + OnPropertyChanged(nameof(SelectedAnimationStyleOption)); + OnPropertyChanged(nameof(BackgroundBlurRadius)); OnPropertyChanged(nameof(IsBackgroundImageMode)); OnPropertyChanged(nameof(IsSolidBackgroundMode)); OnPropertyChanged(nameof(IsGradientBackgroundMode)); diff --git a/SecRandom/Views/SettingsPages/Notification/NotificationChannelSettingsContent.axaml b/SecRandom/Views/SettingsPages/Notification/NotificationChannelSettingsContent.axaml index 627cc72c8..951cbc729 100644 --- a/SecRandom/Views/SettingsPages/Notification/NotificationChannelSettingsContent.axaml +++ b/SecRandom/Views/SettingsPages/Notification/NotificationChannelSettingsContent.axaml @@ -33,73 +33,6 @@ Glyph="{sr:Fi SettingsFilled}" Margin="0 0 0 4" /> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/SecRandom/Views/SettingsPages/Notification/NotificationChannelSettingsPageBase.cs b/SecRandom/Views/SettingsPages/Notification/NotificationChannelSettingsPageBase.cs index b7c7e79b8..4c9d79179 100644 --- a/SecRandom/Views/SettingsPages/Notification/NotificationChannelSettingsPageBase.cs +++ b/SecRandom/Views/SettingsPages/Notification/NotificationChannelSettingsPageBase.cs @@ -1,4 +1,3 @@ -using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Threading.Tasks; @@ -9,7 +8,6 @@ using SecRandom.Core.Abstraction; using SecRandom.Core.Models.SubConfigs; using SecRandom.Core.Services.Config; -using SecRandom.Services.Notification; using SecRandom.ViewModels; using LR = SecRandom.Langs.SettingsPages.Notification.Resources; @@ -29,9 +27,6 @@ protected NotificationChannelSettingsPageBase() { ChannelSettings = SelectChannelSettings(ViewModel.Config.NotificationSettings); NotificationServiceOptions = BuildNotificationServiceOptions(); - MonitorOptions = [new MonitorOption("", Text("Not specified", "O_Monitor_Unspecified"))]; - if (!string.IsNullOrWhiteSpace(ChannelSettings.EnabledMonitor)) - MonitorOptions.Add(new MonitorOption(ChannelSettings.EnabledMonitor, ChannelSettings.EnabledMonitor)); DataContext = this; Loaded += OnLoaded; Unloaded += OnUnloaded; @@ -39,18 +34,6 @@ protected NotificationChannelSettingsPageBase() public ViewModelBase ViewModel { get; } = IAppHost.GetService(); public NotificationChannelSettings ChannelSettings { get; } - public ObservableCollection MonitorOptions { get; } - public MonitorOption? SelectedMonitor - { - get => MonitorOptions.FirstOrDefault(option => option.Value == ChannelSettings.EnabledMonitor); - set - { - if (value is null || value.Value == ChannelSettings.EnabledMonitor) - return; - - ChannelSettings.EnabledMonitor = value.Value; - } - } public IReadOnlyList NotificationServiceOptions { get; private set; } public NotificationServiceOption SelectedNotificationServiceOption { @@ -80,18 +63,6 @@ event PropertyChangedEventHandler? INotifyPropertyChanged.PropertyChanged add => NotifyPropertyChanged += value; remove => NotifyPropertyChanged -= value; } - public bool OverrideNotificationWindowSettings - { - get => OverrideSettings?.OverrideNotificationWindowSettings ?? true; - set - { - if (OverrideSettings is null || OverrideSettings.OverrideNotificationWindowSettings == value) - return; - - OverrideSettings.OverrideNotificationWindowSettings = value; - NotifyPropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(OverrideNotificationWindowSettings))); - } - } public bool OverrideServiceSettings { get => OverrideSettings?.OverrideServiceSettings ?? true; @@ -105,21 +76,12 @@ public bool OverrideServiceSettings } } public virtual string BasicSettingsTitle => Text(nameof(BasicSettingsTitle), "S_Common_BasicSettings"); - public virtual string NotificationWindowSettingsTitle => Text(nameof(NotificationWindowSettingsTitle), "S_Common_NotificationWindowSettings"); public virtual string OverridableSettingsTitle => Text(nameof(OverridableSettingsTitle), "S_Common_OverridableSettings"); public virtual string OverrideTitle => Text(nameof(OverrideTitle), "C_EnableOverride"); public abstract string EnabledTitle { get; } public abstract string EnabledDescription { get; } public virtual string AnimationTitle => Text(nameof(AnimationTitle), "S_Default_Animation"); public virtual string AnimationDescription => Text(nameof(AnimationDescription), "S_Default_Animation_D"); - public virtual string WindowPositionTitle => Text(nameof(WindowPositionTitle), "S_Default_WindowPosition"); - public virtual string WindowPositionDescription => Text(nameof(WindowPositionDescription), "S_Default_WindowPosition_D"); - public virtual string EnabledMonitorTitle => Text(nameof(EnabledMonitorTitle), "S_Common_EnabledMonitor"); - public virtual string EnabledMonitorDescription => Text(nameof(EnabledMonitorDescription), "S_Common_EnabledMonitor_D"); - public virtual string OffsetTitle => Text(nameof(OffsetTitle), "S_Default_Offset"); - public virtual string OffsetDescription => Text(nameof(OffsetDescription), "S_Default_Offset_D"); - public virtual string TransparencyTitle => Text(nameof(TransparencyTitle), "S_Default_Transparency"); - public virtual string TransparencyDescription => Text(nameof(TransparencyDescription), "S_Default_Transparency_D"); public virtual string NotificationServiceTitle => Text(nameof(NotificationServiceTitle), "S_Common_NotificationService"); public virtual string NotificationServiceTypeTitle => Text(nameof(NotificationServiceTypeTitle), "S_Common_NotificationServiceType"); public virtual string NotificationServiceTypeDescription => Text(nameof(NotificationServiceTypeDescription), "S_Common_NotificationServiceType_D"); @@ -260,36 +222,6 @@ private void OnLoaded(object? sender, RoutedEventArgs e) NotifyPropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(NotificationServiceOptions))); NotifyPropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(SelectedNotificationServiceOption))); } - - var selectedMonitor = ChannelSettings.EnabledMonitor; - var topLevel = TopLevel.GetTopLevel(this); - if (topLevel?.Screens is not null) - { - var nativeNames = WindowsMonitorNameProvider.GetNames(); - for (var index = 0; index < topLevel.Screens.All.Count; index++) - { - var screen = topLevel.Screens.All[index]; - nativeNames.TryGetValue(screen.Bounds.Position, out var nativeName); - var displayName = string.IsNullOrWhiteSpace(screen.DisplayName) ? nativeName : screen.DisplayName; - var identifier = NotificationMonitorIdentifier.Get(displayName, screen.Bounds); - if (MonitorOptions.All(option => option.Value != identifier)) - { - var label = NotificationMonitorIdentifier.GetLabel( - displayName, - screen.Bounds, - screen.IsPrimary, - index, - Text("{0}: {1}x{2} @ {3},{4}{5}", "O_Monitor_Label"), - Text("(主显示器)", "O_Monitor_Primary")); - MonitorOptions.Add(new MonitorOption(identifier, label)); - } - } - } - - if (!string.IsNullOrWhiteSpace(selectedMonitor) - && MonitorOptions.All(option => option.Value != selectedMonitor)) - MonitorOptions.Add(new MonitorOption(selectedMonitor, selectedMonitor)); - } private void SettingsOnPropertyChanged(object? sender, PropertyChangedEventArgs e) @@ -298,8 +230,6 @@ private void SettingsOnPropertyChanged(object? sender, PropertyChangedEventArgs or nameof(NotificationChannelSettings.Animation)) OverrideSettings?.OverrideBasicSettings = true; - if (e.PropertyName == nameof(NotificationChannelSettings.EnabledMonitor)) - NotifyPropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(SelectedMonitor))); if (e.PropertyName == nameof(NotificationChannelSettings.NotificationServiceType)) { NotifyPropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(UsesExternalNotificationServiceOnly))); @@ -309,6 +239,4 @@ or nameof(NotificationChannelSettings.Animation)) } } -public sealed record MonitorOption(string Value, string Label); - public sealed record NotificationServiceOption(int Value, string Label); diff --git a/SecRandom/Views/SettingsPages/Notification/NotificationFloatingWindowSettingsPage.axaml b/SecRandom/Views/SettingsPages/Notification/NotificationFloatingWindowSettingsPage.axaml new file mode 100644 index 000000000..7b89d1d3e --- /dev/null +++ b/SecRandom/Views/SettingsPages/Notification/NotificationFloatingWindowSettingsPage.axaml @@ -0,0 +1,90 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/SecRandom/Views/SettingsPages/Notification/NotificationFloatingWindowSettingsPage.axaml.cs b/SecRandom/Views/SettingsPages/Notification/NotificationFloatingWindowSettingsPage.axaml.cs new file mode 100644 index 000000000..ba22b9a46 --- /dev/null +++ b/SecRandom/Views/SettingsPages/Notification/NotificationFloatingWindowSettingsPage.axaml.cs @@ -0,0 +1,188 @@ +using System; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Linq; +using Avalonia.Controls; +using Avalonia.Interactivity; +using Avalonia.Threading; +using SecRandom.Core.Abstraction; +using SecRandom.Core.Attributes; +using SecRandom.Core.Icons; +using SecRandom.Core.Models.SubConfigs; +using SecRandom.Core.Services.Config; +using SecRandom.Helpers; +using SecRandom.Services.Notification; +using LR = SecRandom.Langs.SettingsPages.Notification.Resources; + +namespace SecRandom.Views.SettingsPages.Notification; + +/// +/// 内置通知浮窗(闪抽结果浮窗)的窗口设置。位置、显示器、偏移与不透明度只有一份,写在 +/// 上;各通知渠道只保留启用、动画、通知服务与交付时长, +/// 渠道的窗口覆盖字段已无界面入口,因此新页面的每次编辑就是所有渠道看到的浮窗几何。 +/// +[PageInfo("settings.notification.floatingWindow", FluentIcons.PictureInPictureFilled, "settings.notification")] +public partial class NotificationFloatingWindowSettingsPage : UserControl, INotifyPropertyChanged +{ + private const string MonitorLabelFormatKey = "O_Monitor_Label"; + private const string MonitorPrimaryKey = "O_Monitor_Primary"; + + private bool _savePending; + private DispatcherTimer? _saveTimer; + private event PropertyChangedEventHandler? NotifyPropertyChanged; + + public NotificationFloatingWindowSettingsPage() + { + InitializeComponent(); + Settings = ConfigHandler.Data.NotificationSettings.Default; + MonitorOptions = [new MonitorOption("", Text("Not specified", "O_Monitor_Unspecified"))]; + if (!string.IsNullOrWhiteSpace(Settings.EnabledMonitor)) + MonitorOptions.Add(new MonitorOption(Settings.EnabledMonitor, Settings.EnabledMonitor)); + + DataContext = this; + Loaded += OnPageLoaded; + Unloaded += OnPageUnloaded; + } + + private MainConfigHandler ConfigHandler { get; } = IAppHost.GetService(); + + public NotificationChannelSettings Settings { get; } + + public ObservableCollection MonitorOptions { get; } + + public MonitorOption? SelectedMonitor + { + get => MonitorOptions.FirstOrDefault(option => option.Value == Settings.EnabledMonitor); + set + { + if (value is null || value.Value == Settings.EnabledMonitor) + return; + + Settings.EnabledMonitor = value.Value; + } + } + + /// 低配模式会强制关闭自适应前景色,开关因此置灰。 + public bool IsAdaptiveForegroundAvailable => !UiRenderQuality.IsLowSpecMode; + + /// + /// 开关显示的生效值:低配模式下一律显示为关闭,但不去改用户已保存的偏好, + /// 退出低配模式后开关重新启用并恢复用户自己的选择。 + /// + public bool AdaptiveForegroundEnabled + { + get => IsAdaptiveForegroundAvailable && Settings.AdaptiveForeground; + set + { + if (!IsAdaptiveForegroundAvailable || Settings.AdaptiveForeground == value) + return; + + Settings.AdaptiveForeground = value; + } + } + + event PropertyChangedEventHandler? INotifyPropertyChanged.PropertyChanged + { + add => NotifyPropertyChanged += value; + remove => NotifyPropertyChanged -= value; + } + + private void OnPageLoaded(object? sender, RoutedEventArgs e) + { + Settings.PropertyChanged -= SettingsOnPropertyChanged; + Settings.PropertyChanged += SettingsOnPropertyChanged; + + RefreshMonitorOptions(); + + // 低配模式可能在基本设置页刚被改过;回到本页时按当前值重算开关的可用性与显示态。 + NotifyPropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(IsAdaptiveForegroundAvailable))); + NotifyPropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(AdaptiveForegroundEnabled))); + } + + private void OnPageUnloaded(object? sender, RoutedEventArgs e) + { + // 切页或关窗时把挂起的编辑立刻落盘,否则防抖窗口里的最后一次拖动会丢。 + CommitSettings(); + + Settings.PropertyChanged -= SettingsOnPropertyChanged; + _saveTimer?.Stop(); + _saveTimer = null; + } + + /// 显示器名称随显示器插拔变化,每次加载与打开下拉框时都重建一次候选列表。 + private void RefreshMonitorOptions() + { + var selectedMonitor = Settings.EnabledMonitor; + var topLevel = TopLevel.GetTopLevel(this); + if (topLevel?.Screens is not null) + { + var nativeNames = WindowsMonitorNameProvider.GetNames(); + for (var index = 0; index < topLevel.Screens.All.Count; index++) + { + var screen = topLevel.Screens.All[index]; + nativeNames.TryGetValue(screen.Bounds.Position, out var nativeName); + var displayName = string.IsNullOrWhiteSpace(screen.DisplayName) ? nativeName : screen.DisplayName; + var identifier = NotificationMonitorIdentifier.Get(displayName, screen.Bounds); + if (MonitorOptions.All(option => option.Value != identifier)) + { + var label = NotificationMonitorIdentifier.GetLabel( + displayName, + screen.Bounds, + screen.IsPrimary, + index, + Text("{0}: {1}x{2} @ {3},{4}{5}", MonitorLabelFormatKey), + Text("(主显示器)", MonitorPrimaryKey)); + MonitorOptions.Add(new MonitorOption(identifier, label)); + } + } + } + + if (!string.IsNullOrWhiteSpace(selectedMonitor) + && MonitorOptions.All(option => option.Value != selectedMonitor)) + MonitorOptions.Add(new MonitorOption(selectedMonitor, selectedMonitor)); + + NotifyPropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(SelectedMonitor))); + } + + private void SettingsOnPropertyChanged(object? sender, PropertyChangedEventArgs e) + { + if (e.PropertyName == nameof(NotificationChannelSettings.EnabledMonitor)) + NotifyPropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(SelectedMonitor))); + + // 子配置(NotificationSettings.Default)不会自动落盘,页面的每次编辑都要显式保存一次。 + ScheduleSave(); + } + + /// 排一次 400ms 后的落盘,连续编辑(滑杆拖动)会被下一次调用重置。 + private void ScheduleSave() + { + _savePending = true; + + if (_saveTimer is null) + { + _saveTimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(400) }; + _saveTimer.Tick += (_, _) => CommitSettings(); + } + + _saveTimer.Stop(); + _saveTimer.Start(); + } + + private void CommitSettings() + { + _saveTimer?.Stop(); + if (!_savePending) + return; + + _savePending = false; + ConfigHandler.Save(); + } + + private static string Text(string fallback, string key) + { + return LR.ResourceManager.GetString(key, LR.Culture) ?? fallback; + } +} + +/// 显示器下拉框的一项。 是持久化的显示器标识,空串表示跟随主显示器。 +public sealed record MonitorOption(string Value, string Label); \ No newline at end of file From 24f791e894caac911019bb310f9c9987de0d9053 Mon Sep 17 00:00:00 2001 From: lzy98276 Date: Sat, 14 Nov 2026 19:35:09 +0800 Subject: [PATCH 06/26] =?UTF-8?q?feat(data-root):=20=E6=95=B0=E6=8D=AE?= =?UTF-8?q?=E7=9B=AE=E5=BD=95=E5=8F=AF=E9=85=8D=E7=BD=AE=E5=8F=AF=E8=BF=81?= =?UTF-8?q?=E7=A7=BB=EF=BC=8C=E5=AE=89=E8=A3=85=E7=89=88=E6=94=B9=E7=94=A8?= =?UTF-8?q?=20per-user=20=E6=A0=87=E5=87=86=E4=BD=8D=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 数据根不再等同于程序目录下的 data/,桌面端改为按优先级解析: --data-root > SECRANDOM_DATA_ROOT > 锚点 data-root.json > 旧位置认领 > 模式默认。 - 安装版默认使用 per-user 标准位置(Windows %LOCALAPPDATA%\SecRandom\data, macOS ~/Library/Application Support/SecRandom/data,Linux ${XDG_CONFIG_HOME:-~/.config}/secrandom/data),不再把数据写进安装目录; 便携版继续使用 <包根>/data,锚点写在数据根之外。 - 旧位置(安装目录内 data/、app-*/data)会被识别认领:便携版把落在 payload 里的 数据迁回包根,安装版只在设置页提示,不自动搬动。 - 新增两阶段迁移事务:设置页校验并写 data-root-journal.json,带 --data-root-migration 重启,迁移窗口在同卷 staging 复制、校验(小文件 SHA-256,大媒体长度+修改时间)、改写根绝对路径后 rename 提交;锚点写入是唯一 提交点,失败时目标回退为 staging、源保持完整,旧目录保留为 .migrated-<时间戳>。 - 新增设置页 settings.general.storage:显示当前根/来源/锚点、三种模式切换、 目录选择、迁移预检与授权(复用 RestartApplication 验证门)、旧位置清单。 - 持久化图片路径改为根相对(DataPathReference.ToStored/Resolve),迁移时 DataRootPathRewriter 改写 list/**/*.json 的 ImagePath 与证明队列的 path。 - 便携更新部署前拒绝「数据根位于被替换 payload 内」的情况并提示迁移。 - 新增 22 例数据目录测试(解析优先级、锚点读写、路径相对化、改写、迁移引擎)。 --- .../DataRoot/DataPathReferenceTests.cs | 44 ++ .../DataRoot/DataRootAnchorStoreTests.cs | 52 ++ .../DataRoot/DataRootMigrationEngineTests.cs | 145 +++++ .../DataRoot/DataRootPathRewriterTests.cs | 43 ++ .../DataRoot/DataRootTestEnvironment.cs | 61 ++ .../DataRoot/DesktopDataRootResolverTests.cs | 149 +++++ .../DesktopDataRootPreparationTests.cs | 64 +- .../DataRoot/DataRootMigrationEngine.cs | 588 ++++++++++++++++++ .../DataRoot/DataRootMigrationJournal.cs | 123 ++++ .../Services/DataRoot/DataRootPathRewriter.cs | 176 ++++++ SecRandom.Desktop/Program.cs | 42 +- SecRandom.Shared/AGENTS.md | 5 +- .../DataRoot/DataPathReference.cs | 81 +++ .../DataRoot/DataRootAnchorStore.cs | 99 +++ .../DataRoot/DataRootCommandLine.cs | 101 +++ .../DataRoot/DataRootLaunchState.cs | 13 + SecRandom.Shared/DataRoot/DataRootPaths.cs | 235 +++++++ SecRandom.Shared/DataRoot/DataRootTypes.cs | 167 +++++ .../DataRoot/DesktopDataRootResolver.cs | 185 ++++++ SecRandom.Shared/Utils.cs | 265 ++++---- .../DrawImageAttachedSettingsControl.axaml.cs | 7 +- SecRandom/Langs/Common/Resources.Designer.cs | 23 + SecRandom/Langs/Common/Resources.en-US.resx | 10 + SecRandom/Langs/Common/Resources.ja-JP.resx | 10 + SecRandom/Langs/Common/Resources.resx | 11 + .../DataRootMigration/Resources.Designer.cs | 177 ++++++ .../DataRootMigration/Resources.en-US.resx | 31 + .../DataRootMigration/Resources.ja-JP.resx | 31 + .../Langs/DataRootMigration/Resources.resx | 59 ++ .../General/Storage/Resources.Designer.cs | 337 ++++++++++ .../General/Storage/Resources.en-US.resx | 165 +++++ .../General/Storage/Resources.ja-JP.resx | 165 +++++ .../General/Storage/Resources.resx | 165 +++++ .../SettingsPages/Update/Resources.en-US.resx | 2 +- .../SettingsPages/Update/Resources.ja-JP.resx | 2 +- .../Langs/SettingsPages/Update/Resources.resx | 1 + SecRandom/SecRandom.csproj | 22 + .../Mobile/MobileMediaLibraryService.cs | 5 +- .../FullscreenNotificationComposer.cs | 4 +- .../Services/Updates/UpdateCenterService.cs | 1 + .../MainPages/LotteryPageViewModel.cs | 3 +- .../MainPages/QuickDrawPageViewModel.cs | 3 +- .../MainPages/RollCallPageViewModel.cs | 3 +- SecRandom/Views/DataRootMigrationWindow.cs | 263 ++++++++ .../FullscreenNotificationWindow.axaml.cs | 6 +- .../General/StorageSettingsPage.axaml | 124 ++++ .../General/StorageSettingsPage.axaml.cs | 321 ++++++++++ .../Picking/BatchAvatarDrawer.axaml.cs | 3 +- 48 files changed, 4453 insertions(+), 139 deletions(-) create mode 100644 SecRandom.Core.Tests/DataRoot/DataPathReferenceTests.cs create mode 100644 SecRandom.Core.Tests/DataRoot/DataRootAnchorStoreTests.cs create mode 100644 SecRandom.Core.Tests/DataRoot/DataRootMigrationEngineTests.cs create mode 100644 SecRandom.Core.Tests/DataRoot/DataRootPathRewriterTests.cs create mode 100644 SecRandom.Core.Tests/DataRoot/DataRootTestEnvironment.cs create mode 100644 SecRandom.Core.Tests/DataRoot/DesktopDataRootResolverTests.cs create mode 100644 SecRandom.Core/Services/DataRoot/DataRootMigrationEngine.cs create mode 100644 SecRandom.Core/Services/DataRoot/DataRootMigrationJournal.cs create mode 100644 SecRandom.Core/Services/DataRoot/DataRootPathRewriter.cs create mode 100644 SecRandom.Shared/DataRoot/DataPathReference.cs create mode 100644 SecRandom.Shared/DataRoot/DataRootAnchorStore.cs create mode 100644 SecRandom.Shared/DataRoot/DataRootCommandLine.cs create mode 100644 SecRandom.Shared/DataRoot/DataRootLaunchState.cs create mode 100644 SecRandom.Shared/DataRoot/DataRootPaths.cs create mode 100644 SecRandom.Shared/DataRoot/DataRootTypes.cs create mode 100644 SecRandom.Shared/DataRoot/DesktopDataRootResolver.cs create mode 100644 SecRandom/Langs/DataRootMigration/Resources.Designer.cs create mode 100644 SecRandom/Langs/DataRootMigration/Resources.en-US.resx create mode 100644 SecRandom/Langs/DataRootMigration/Resources.ja-JP.resx create mode 100644 SecRandom/Langs/DataRootMigration/Resources.resx create mode 100644 SecRandom/Langs/SettingsPages/General/Storage/Resources.Designer.cs create mode 100644 SecRandom/Langs/SettingsPages/General/Storage/Resources.en-US.resx create mode 100644 SecRandom/Langs/SettingsPages/General/Storage/Resources.ja-JP.resx create mode 100644 SecRandom/Langs/SettingsPages/General/Storage/Resources.resx create mode 100644 SecRandom/Views/DataRootMigrationWindow.cs create mode 100644 SecRandom/Views/SettingsPages/General/StorageSettingsPage.axaml create mode 100644 SecRandom/Views/SettingsPages/General/StorageSettingsPage.axaml.cs diff --git a/SecRandom.Core.Tests/DataRoot/DataPathReferenceTests.cs b/SecRandom.Core.Tests/DataRoot/DataPathReferenceTests.cs new file mode 100644 index 000000000..0d54f4e39 --- /dev/null +++ b/SecRandom.Core.Tests/DataRoot/DataPathReferenceTests.cs @@ -0,0 +1,44 @@ +using SecRandom.Shared.DataRoot; + +namespace SecRandom.Core.Tests.DataRoot; + +public sealed class DataPathReferenceTests +{ + [Fact] + public void ToStored_RewritesPathsInsideTheRootAsRelative() + { + using var env = new DataRootTestEnvironment(); + var root = env.CreateDirectory("data"); + var image = env.WriteFile("data/images/student.png", "x"); + + var stored = DataPathReference.ToStored(image, root); + + Assert.Equal("images/student.png", stored); + Assert.Equal(image, DataPathReference.Resolve(stored, root)); + } + + [Fact] + public void ToStored_KeepsExternalAbsolutePathsUntouched() + { + using var env = new DataRootTestEnvironment(); + var root = env.CreateDirectory("data"); + var external = env.WriteFile("pictures/photo.jpg", "x"); + + var stored = DataPathReference.ToStored(external, root); + + Assert.Equal(DataRootPaths.Normalize(external), DataRootPaths.Normalize(stored)); + Assert.True(Path.IsPathRooted(stored)); + } + + [Fact] + public void Resolve_LeavesAbsoluteAndUrlValuesAlone() + { + using var env = new DataRootTestEnvironment(); + var root = env.CreateDirectory("data"); + var absolute = env.PathOf("elsewhere", "a.png"); + + Assert.False(DataPathReference.IsStoredRelative(absolute)); + Assert.Equal(absolute, DataPathReference.Resolve(absolute, root)); + Assert.False(DataPathReference.IsStoredRelative("https://example.com/a.png")); + } +} \ No newline at end of file diff --git a/SecRandom.Core.Tests/DataRoot/DataRootAnchorStoreTests.cs b/SecRandom.Core.Tests/DataRoot/DataRootAnchorStoreTests.cs new file mode 100644 index 000000000..3bcdae5e6 --- /dev/null +++ b/SecRandom.Core.Tests/DataRoot/DataRootAnchorStoreTests.cs @@ -0,0 +1,52 @@ +using SecRandom.Shared.DataRoot; + +namespace SecRandom.Core.Tests.DataRoot; + +public sealed class DataRootAnchorStoreTests +{ + [Fact] + public void Write_ThenRead_RoundTripsTheAnchor() + { + using var env = new DataRootTestEnvironment(); + var anchorPath = env.PathOf("anchor", DataRootPaths.AnchorFileName); + + DataRootAnchorStore.Write(anchorPath, new DataRootAnchor + { + Mode = DataRootModeExtensions.ToStorageValue(DataRootMode.Package), + DataRoot = env.CreateDirectory("data"), + PackageKind = "portable-zip" + }); + + var result = DataRootAnchorStore.Read(anchorPath); + + Assert.Equal(DataRootAnchorStatus.Valid, result.Status); + Assert.NotNull(result.Anchor); + Assert.Equal(DataRootMode.Package, DataRootModeExtensions.Parse(result.Anchor!.Mode)); + Assert.Equal(DataRootPaths.Normalize(env.PathOf("data")), result.Anchor.DataRoot); + Assert.Equal("portable-zip", result.Anchor.PackageKind); + } + + [Fact] + public void Read_MissingAnchor_ReportsMissingWithoutThrowing() + { + using var env = new DataRootTestEnvironment(); + + var result = DataRootAnchorStore.Read(env.PathOf("anchor", DataRootPaths.AnchorFileName)); + + Assert.Equal(DataRootAnchorStatus.Missing, result.Status); + Assert.Null(result.Anchor); + } + + [Fact] + public void Read_UnsupportedSchema_ReportsInvalid() + { + using var env = new DataRootTestEnvironment(); + var anchorPath = env.WriteFile("anchor/data-root.json", + "{\"schemaVersion\":99,\"mode\":\"standard\",\"dataRoot\":\"/tmp/x\"}"); + + var result = DataRootAnchorStore.Read(anchorPath); + + Assert.Equal(DataRootAnchorStatus.Invalid, result.Status); + Assert.False(string.IsNullOrWhiteSpace(result.ErrorMessage)); + } +} \ No newline at end of file diff --git a/SecRandom.Core.Tests/DataRoot/DataRootMigrationEngineTests.cs b/SecRandom.Core.Tests/DataRoot/DataRootMigrationEngineTests.cs new file mode 100644 index 000000000..54e9e55a0 --- /dev/null +++ b/SecRandom.Core.Tests/DataRoot/DataRootMigrationEngineTests.cs @@ -0,0 +1,145 @@ +using SecRandom.Shared.DataRoot; +using SecRandom.Core.Services.DataRoot; + +namespace SecRandom.Core.Tests.DataRoot; + +public sealed class DataRootMigrationEngineTests +{ + [Fact] + public void Validate_RejectsATargetInsideTheRunningPayload() + { + using var env = new DataRootTestEnvironment(); + var appDirectory = env.CreateDirectory("install"); + var source = env.CreateDirectory("source"); + + var error = DataRootMigrationEngine.Validate( + source, + Path.Combine(appDirectory, "data"), + appDirectory, + out var detail); + + Assert.Equal(DataRootMigrationErrorCode.TargetInsideApp, error); + Assert.False(string.IsNullOrWhiteSpace(detail)); + } + + [Fact] + public void Validate_RejectsTargetsThatNestWithTheSource() + { + using var env = new DataRootTestEnvironment(); + var appDirectory = env.CreateDirectory("install"); + var source = env.CreateDirectory("source"); + + Assert.Equal( + DataRootMigrationErrorCode.TargetInsideSource, + DataRootMigrationEngine.Validate( + source, Path.Combine(source, "nested"), appDirectory, out _)); + + var existingTarget = env.CreateDirectory("existing"); + Assert.Equal( + DataRootMigrationErrorCode.SourceInsideTarget, + DataRootMigrationEngine.Validate( + existingTarget, Path.GetDirectoryName(existingTarget)!, appDirectory, out _)); + } + + [Fact] + public void Validate_RejectsANonEmptyTarget() + { + using var env = new DataRootTestEnvironment(); + var appDirectory = env.CreateDirectory("install"); + var source = env.CreateDirectory("source"); + var target = env.CreateDirectory("target"); + env.WriteFile("target/keep.txt", "x"); + + var error = DataRootMigrationEngine.Validate(source, target, appDirectory, out _); + + Assert.Equal(DataRootMigrationErrorCode.TargetNotEmpty, error); + } + + [Fact] + public void Run_MovesDataRewritesRelativePathsAndKeepsTheSourceAsAnArchive() + { + using var env = new DataRootTestEnvironment(); + var appDirectory = env.CreateDirectory("install"); + var source = env.CreateDirectory("source"); + var target = env.PathOf("target"); + + env.WriteFile("source/config/settings.json", "{\"language\":\"zh-CN\"}"); + var image = env.WriteFile("source/images/student.png", "png"); + env.WriteFile("source/list/students.json", + "{\"ImagePath\":\"" + image.Replace("\\", "\\\\") + "\"}"); + env.WriteFile("source/proofs/attestation-queue.json", + "{\"items\":[{\"path\":\"" + env.PathOf("source", "proofs", "a.srproof.json").Replace("\\", "\\\\") + + "\"}]}"); + + var anchorPath = env.PathOf("anchor", DataRootPaths.AnchorFileName); + var anchorDirectory = Path.GetDirectoryName(anchorPath)!; + var journalPath = DataRootMigrationJournalStore.GetPath(anchorDirectory); + var transactionId = Guid.NewGuid().ToString("N"); + var journal = new DataRootMigrationJournal + { + TransactionId = transactionId, + State = DataRootMigrationState.Pending, + SourceRoot = source, + TargetRoot = Path.GetFullPath(target), + StagingRoot = DataRootMigrationEngine.GetStagingPath(target, transactionId), + Mode = DataRootMode.Custom, + AnchorPath = anchorPath + }; + + var engine = new DataRootMigrationEngine(journal, journalPath, appDirectory); + var result = engine.Run(progress: null, CancellationToken.None); + + Assert.True(result.Success, result.Detail); + Assert.Equal(DataRootMigrationErrorCode.None, result.Code); + Assert.Equal(Path.GetFullPath(target), result.TargetRoot); + Assert.True(File.Exists(env.PathOf("target", "config", "settings.json"))); + Assert.True(File.Exists(env.PathOf("target", "images", "student.png"))); + + var students = env.ReadFile("target/list/students.json"); + Assert.Contains("\"ImagePath\":\"images/student.png\"", students, StringComparison.Ordinal); + var queue = env.ReadFile("target/proofs/attestation-queue.json"); + Assert.Contains("\"path\":\"proofs/a.srproof.json\"", queue, StringComparison.Ordinal); + + var anchor = DataRootAnchorStore.Read(anchorPath); + Assert.Equal(DataRootAnchorStatus.Valid, anchor.Status); + Assert.Equal(DataRootMode.Custom, DataRootModeExtensions.Parse(anchor.Anchor!.Mode)); + + Assert.False(Directory.Exists(source)); + Assert.NotNull(result.SourceArchiveRoot); + Assert.True(Directory.Exists(result.SourceArchiveRoot)); + Assert.False(File.Exists(journalPath)); + } + + [Fact] + public void Run_TargetThatIsNotWritable_ReportsTheFailureWithoutMovingAnything() + { + using var env = new DataRootTestEnvironment(); + var appDirectory = env.CreateDirectory("install"); + var source = env.CreateDirectory("source"); + env.WriteFile("source/config/settings.json", "{}"); + var anchorPath = env.PathOf("anchor", DataRootPaths.AnchorFileName); + var journalPath = DataRootMigrationJournalStore.GetPath(Path.GetDirectoryName(anchorPath)!); + var transactionId = Guid.NewGuid().ToString("N"); + var target = env.PathOf("blocked", "target"); + // A file where the parent directory should be makes the staging directory impossible to create. + env.WriteFile("blocked", "not a directory"); + + var journal = new DataRootMigrationJournal + { + TransactionId = transactionId, + State = DataRootMigrationState.Pending, + SourceRoot = source, + TargetRoot = target, + StagingRoot = DataRootMigrationEngine.GetStagingPath(target, transactionId), + Mode = DataRootMode.Custom, + AnchorPath = anchorPath + }; + + var result = new DataRootMigrationEngine(journal, journalPath, appDirectory) + .Run(progress: null, CancellationToken.None); + + Assert.False(result.Success); + Assert.True(Directory.Exists(source)); + Assert.False(Directory.Exists(target)); + } +} \ No newline at end of file diff --git a/SecRandom.Core.Tests/DataRoot/DataRootPathRewriterTests.cs b/SecRandom.Core.Tests/DataRoot/DataRootPathRewriterTests.cs new file mode 100644 index 000000000..01c1f9c41 --- /dev/null +++ b/SecRandom.Core.Tests/DataRoot/DataRootPathRewriterTests.cs @@ -0,0 +1,43 @@ +using SecRandom.Core.Services.DataRoot; + +namespace SecRandom.Core.Tests.DataRoot; + +public sealed class DataRootPathRewriterTests +{ + [Fact] + public void RewriteStaging_MakesRootedReferencesRelativeAndKeepsExternalOnes() + { + using var env = new DataRootTestEnvironment(); + var staging = env.CreateDirectory("staging"); + var oldRoot = env.PathOf("old-data"); + var newRoot = env.PathOf("new-data"); + var internalImage = env.PathOf("old-data", "images", "a.png"); + var externalImage = env.PathOf("pictures", "outside.png"); + + env.WriteFile("staging/list/students.json", + "{\"members\":[{\"ImagePath\":\"" + internalImage.Replace("\\", "\\\\") + "\"}," + + "{\"ImagePath\":\"" + externalImage.Replace("\\", "\\\\") + "\"}]}"); + + DataRootPathRewriter.RewriteStaging(staging, oldRoot, newRoot); + + var rewritten = env.ReadFile("staging/list/students.json"); + Assert.Contains("\"ImagePath\":\"images/a.png\"", rewritten, StringComparison.Ordinal); + Assert.Contains(externalImage.Replace("\\", "\\\\"), rewritten, StringComparison.Ordinal); + } + + [Fact] + public void RewriteStaging_LeavesUnrelatedFilesByteIdentical() + { + using var env = new DataRootTestEnvironment(); + var staging = env.CreateDirectory("staging"); + const string original = "{\"unrelated\":\"旧根/" + "not-a-path\"}"; + env.WriteFile("staging/config/settings.json", original); + + DataRootPathRewriter.RewriteStaging( + staging, + env.PathOf("old-data"), + env.PathOf("new-data")); + + Assert.Equal(original, env.ReadFile("staging/config/settings.json")); + } +} \ No newline at end of file diff --git a/SecRandom.Core.Tests/DataRoot/DataRootTestEnvironment.cs b/SecRandom.Core.Tests/DataRoot/DataRootTestEnvironment.cs new file mode 100644 index 000000000..c12356212 --- /dev/null +++ b/SecRandom.Core.Tests/DataRoot/DataRootTestEnvironment.cs @@ -0,0 +1,61 @@ +using SecRandom.Shared.DataRoot; + +namespace SecRandom.Core.Tests.DataRoot; + +/// Disposable temp tree shared by the data-root tests; every path stays inside . +internal sealed class DataRootTestEnvironment : IDisposable +{ + public string Root { get; } = + Path.Combine(Path.GetTempPath(), "SecRandom", "data-root-tests", Guid.NewGuid().ToString("N")); + + public string PathOf(params string[] parts) + { + return Path.Combine([Root, .. parts]); + } + + public string CreateDirectory(params string[] parts) + { + var path = PathOf(parts); + Directory.CreateDirectory(path); + return path; + } + + public string WriteFile(string relativePath, string content) + { + var path = PathOf(relativePath.Split('/', '\\')); + var directory = Path.GetDirectoryName(path); + if (!string.IsNullOrEmpty(directory)) + Directory.CreateDirectory(directory); + File.WriteAllText(path, content); + return path; + } + + public string ReadFile(string relativePath) + { + return File.ReadAllText(PathOf(relativePath.Split('/', '\\'))); + } + + public string WritePayloadMarker(string payloadDirectory, string packageKind = "portable-zip") + { + Directory.CreateDirectory(payloadDirectory); + var path = Path.Combine(payloadDirectory, DataRootPaths.PayloadMarkerFileName); + File.WriteAllText( + path, + "{\"schemaVersion\":1,\"product\":\"SecRandom\",\"rid\":\"win-x64\",\"packageKind\":\"" + + packageKind + "\",\"runtimeKind\":\"self-contained\"}"); + return path; + } + + public void Dispose() + { + try + { + if (Directory.Exists(Root)) + Directory.Delete(Root, recursive: true); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + // A leftover temp tree must never fail a test run. + } + } +} \ No newline at end of file diff --git a/SecRandom.Core.Tests/DataRoot/DesktopDataRootResolverTests.cs b/SecRandom.Core.Tests/DataRoot/DesktopDataRootResolverTests.cs new file mode 100644 index 000000000..49c918ea5 --- /dev/null +++ b/SecRandom.Core.Tests/DataRoot/DesktopDataRootResolverTests.cs @@ -0,0 +1,149 @@ +using SecRandom.Shared.DataRoot; + +namespace SecRandom.Core.Tests.DataRoot; + +public sealed class DesktopDataRootResolverTests +{ + [Fact] + public void FreshInstalled_WithWritableInstallDirectory_UsesStandardRoot() + { + using var env = new DataRootTestEnvironment(); + var appDirectory = env.CreateDirectory("install"); + + var resolution = DesktopDataRootResolver.Resolve(Options(env, appDirectory)); + + Assert.False(resolution.IsPortablePackage); + Assert.Equal(DataRootMode.Standard, resolution.Mode); + Assert.Equal(DataRootSource.ModeDefault, resolution.Source); + Assert.Equal(DataRootPaths.Normalize(env.PathOf("standard-data")), resolution.DataRoot); + Assert.False(resolution.NeedsMigrationNotice); + } + + [Fact] + public void Installed_WithLegacyInstallDirectoryData_ClaimsItAndAsksForAMigration() + { + using var env = new DataRootTestEnvironment(); + var appDirectory = env.CreateDirectory("install"); + env.WriteFile("install/data/config/settings.json", "{}"); + + var resolution = DesktopDataRootResolver.Resolve(Options(env, appDirectory)); + + Assert.Equal(DataRootMode.Package, resolution.Mode); + Assert.Equal(DataRootSource.Legacy, resolution.Source); + Assert.Equal(DataRootPaths.Normalize(env.PathOf("install", "data")), resolution.DataRoot); + Assert.True(resolution.NeedsMigrationNotice); + } + + [Fact] + public void Installed_WithStandardData_PrefersStandardWithoutNotice() + { + using var env = new DataRootTestEnvironment(); + var appDirectory = env.CreateDirectory("install"); + env.WriteFile("install/data/config/settings.json", "{}"); + env.WriteFile("standard-data/config/settings.json", "{}"); + + var resolution = DesktopDataRootResolver.Resolve(Options(env, appDirectory)); + + Assert.Equal(DataRootMode.Standard, resolution.Mode); + Assert.Equal(DataRootSource.ModeDefault, resolution.Source); + Assert.Equal(DataRootPaths.Normalize(env.PathOf("standard-data")), resolution.DataRoot); + Assert.False(resolution.NeedsMigrationNotice); + } + + [Fact] + public void Portable_KeepsDataBesideThePayload() + { + using var env = new DataRootTestEnvironment(); + var packageRoot = env.CreateDirectory("portable"); + var appDirectory = env.CreateDirectory("portable", "app-3.0.0"); + env.WritePayloadMarker(appDirectory); + env.WriteFile("portable/data/config/settings.json", "{}"); + + var resolution = DesktopDataRootResolver.Resolve(Options( + env, + appDirectory, + packageRoot: packageRoot)); + + Assert.True(resolution.IsPortablePackage); + Assert.Equal(packageRoot, resolution.PackageRoot); + Assert.Equal(DataRootMode.Package, resolution.Mode); + Assert.Equal(DataRootSource.ModeDefault, resolution.Source); + Assert.Equal(DataRootPaths.Normalize(env.PathOf("portable", "data")), resolution.DataRoot); + } + + [Fact] + public void Portable_WithPayloadLocalData_RepairsItOutOfTheVersionDirectory() + { + using var env = new DataRootTestEnvironment(); + var packageRoot = env.CreateDirectory("portable"); + var appDirectory = env.CreateDirectory("portable", "app-3.0.0"); + env.WritePayloadMarker(appDirectory); + env.WriteFile("portable/app-3.0.0/data/config/settings.json", "{}"); + + var resolution = DesktopDataRootResolver.Resolve(Options( + env, + appDirectory, + packageRoot: packageRoot)); + + Assert.Equal(DataRootSource.RepairedPayload, resolution.Source); + Assert.Equal( + DataRootPaths.Normalize(env.PathOf("portable", "app-3.0.0", "data")), + resolution.PayloadDataRootToRepair); + Assert.Equal(DataRootPaths.Normalize(env.PathOf("portable", "data")), resolution.DataRoot); + } + + [Fact] + public void CommandLineOverride_WinsAndStaysOneShot() + { + using var env = new DataRootTestEnvironment(); + var appDirectory = env.CreateDirectory("install"); + env.WriteFile("install/data/config/settings.json", "{}"); + var customRoot = env.PathOf("custom-root"); + + var options = Options(env, appDirectory); + options = options with { CommandLineDataRoot = customRoot }; + var resolution = DesktopDataRootResolver.Resolve(options); + + Assert.Equal(DataRootMode.Custom, resolution.Mode); + Assert.Equal(DataRootSource.CommandLine, resolution.Source); + Assert.Equal(DataRootPaths.Normalize(customRoot), resolution.DataRoot); + Assert.Contains(env.PathOf("install", "data"), + resolution.OtherDataRoots.Select(DataRootPaths.Normalize)); + } + + [Fact] + public void Anchor_IsHonouredOverTheModeDefault() + { + using var env = new DataRootTestEnvironment(); + var appDirectory = env.CreateDirectory("install"); + var options = Options(env, appDirectory); + var customRoot = env.CreateDirectory("moved-data"); + DataRootAnchorStore.Write(options.AnchorPath!, new DataRootAnchor + { + Mode = DataRootModeExtensions.ToStorageValue(DataRootMode.Custom), + DataRoot = customRoot + }); + + var resolution = DesktopDataRootResolver.Resolve(options); + + Assert.Equal(DataRootSource.Anchor, resolution.Source); + Assert.Equal(DataRootMode.Custom, resolution.Mode); + Assert.Equal(DataRootPaths.Normalize(customRoot), resolution.DataRoot); + } + + private static DesktopDataRootOptions Options( + DataRootTestEnvironment env, + string appDirectory, + string? packageRoot = null) + { + return new DesktopDataRootOptions + { + AppDirectory = appDirectory, + PackageRoot = packageRoot ?? appDirectory, + StandardDataRoot = env.PathOf("standard-data"), + StandardAnchorDirectory = env.PathOf("anchor"), + AnchorPath = env.PathOf("anchor", DataRootPaths.AnchorFileName), + WriteAnchor = false + }; + } +} \ No newline at end of file diff --git a/SecRandom.Core.Tests/DesktopDataRootPreparationTests.cs b/SecRandom.Core.Tests/DesktopDataRootPreparationTests.cs index ab15a4737..3724ee699 100644 --- a/SecRandom.Core.Tests/DesktopDataRootPreparationTests.cs +++ b/SecRandom.Core.Tests/DesktopDataRootPreparationTests.cs @@ -1,35 +1,81 @@ using System.Reflection; using SecRandom.Shared; +using SecRandom.Shared.DataRoot; namespace SecRandom.Core.Tests; public sealed class DesktopDataRootPreparationTests : IDisposable { - private readonly string _packageRoot = Path.Combine(Path.GetTempPath(), "SecRandom", "desktop-root-tests", Guid.NewGuid().ToString("N")); + private readonly string _tempRoot = + Path.Combine(Path.GetTempPath(), "SecRandom", "desktop-root-tests", Guid.NewGuid().ToString("N")); [Fact] - public void PrepareDesktopDataRoot_UsesWritableInstalledPackageDirectoryAndLocksTheRoot() + public void PrepareDesktopDataRoot_InstalledWritablePackageDirectory_UsesTheStandardRootAndLocksIt() { ResetDataRootForTests(); + var packageRoot = Directory.CreateDirectory(Path.Combine(_tempRoot, "install")).FullName; + var standardRoot = Path.Combine(_tempRoot, "standard-data"); + var anchorPath = Path.Combine(_tempRoot, "anchor", "data-root.json"); - var result = (Utils.DesktopDataRootPreparationResult)GetUtilsMethod("PrepareDesktopDataRoot", typeof(string), typeof(bool)) - .Invoke(null, [_packageRoot, false])!; + var result = Utils.PrepareDesktopDataRoot(new DesktopDataRootOptions + { + AppDirectory = packageRoot, + PackageRoot = packageRoot, + StandardDataRoot = standardRoot, + AnchorPath = anchorPath, + IsDevelopmentBuild = false + }); - var expectedDataRoot = Path.Combine(Path.GetFullPath(_packageRoot), "data"); + var expectedDataRoot = DataRootPaths.Normalize(standardRoot); Assert.False(result.IsPortablePackage); Assert.True(result.IsWritable); + Assert.Equal(DataRootMode.Standard, result.Mode); + Assert.Equal(DataRootSource.ModeDefault, result.Source); Assert.Equal(expectedDataRoot, result.DataRoot); Assert.Equal(expectedDataRoot, Utils.DataRoot); + Assert.True(File.Exists(anchorPath)); + Assert.Equal(expectedDataRoot, DataRootAnchorStore.Read(anchorPath).Anchor!.DataRoot); - var exception = Assert.Throws(() => ConfigureDataRootForTests(Path.Combine(_packageRoot, "other"))); + var exception = Assert.Throws( + () => ConfigureDataRootForTests(Path.Combine(_tempRoot, "other"))); Assert.IsType(exception.InnerException); } + [Fact] + public void PrepareDesktopDataRoot_InstalledLegacyData_ClaimsItAndRaisesTheMigrationNotice() + { + ResetDataRootForTests(); + var packageRoot = Directory.CreateDirectory(Path.Combine(_tempRoot, "install")).FullName; + var legacyData = Directory.CreateDirectory(Path.Combine(packageRoot, "data")).FullName; + File.WriteAllText(Path.Combine(legacyData, "settings.json"), "{}"); + + var result = Utils.PrepareDesktopDataRoot(new DesktopDataRootOptions + { + AppDirectory = packageRoot, + PackageRoot = packageRoot, + StandardDataRoot = Path.Combine(_tempRoot, "standard-data"), + AnchorPath = Path.Combine(_tempRoot, "anchor", "data-root.json"), + IsDevelopmentBuild = false + }); + + Assert.Equal(DataRootMode.Package, result.Mode); + Assert.Equal(DataRootSource.Legacy, result.Source); + Assert.Equal(DataRootPaths.Normalize(legacyData), result.DataRoot); + Assert.True(result.NeedsMigrationNotice); + } + public void Dispose() { ResetDataRootForTests(); - if (Directory.Exists(_packageRoot)) - Directory.Delete(_packageRoot, recursive: true); + try + { + if (Directory.Exists(_tempRoot)) + Directory.Delete(_tempRoot, recursive: true); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + // Temp cleanup must never fail the run. + } } private static void ConfigureDataRootForTests(string dataRoot) @@ -47,4 +93,4 @@ private static MethodInfo GetUtilsMethod(string name, params Type[] parameterTyp return typeof(Utils).GetMethod(name, BindingFlags.Static | BindingFlags.NonPublic, parameterTypes) ?? throw new InvalidOperationException($"Utils.{name} was not found."); } -} +} \ No newline at end of file diff --git a/SecRandom.Core/Services/DataRoot/DataRootMigrationEngine.cs b/SecRandom.Core/Services/DataRoot/DataRootMigrationEngine.cs new file mode 100644 index 000000000..dccf32121 --- /dev/null +++ b/SecRandom.Core/Services/DataRoot/DataRootMigrationEngine.cs @@ -0,0 +1,588 @@ +using System.Diagnostics; +using System.Security.Cryptography; +using SecRandom.Shared.DataRoot; + +namespace SecRandom.Core.Services.DataRoot; + +public enum DataRootMigrationPhase +{ + Preparing = 0, + Copying = 1, + Verifying = 2, + Committing = 3, + Completed = 4, + Failed = 5 +} + +public enum DataRootMigrationErrorCode +{ + None = 0, + SourceMissing = 1, + SourceEmpty = 2, + TargetInvalid = 3, + TargetEqualsSource = 4, + TargetInsideSource = 5, + SourceInsideTarget = 6, + TargetInsideApp = 7, + TargetNotEmpty = 8, + TargetNotWritable = 9, + AnchorUnavailable = 10, + CopyFailed = 11, + VerifyFailed = 12, + CommitFailed = 13, + Cancelled = 14, + NotFound = 15 +} + +public sealed record DataRootMigrationProgress( + DataRootMigrationPhase Phase, + int CopiedFileCount, + long CopiedByteCount, + int TotalFileCount, + long TotalByteCount, + string? CurrentEntry); + +public sealed record DataRootMigrationResult( + bool Success, + DataRootMigrationErrorCode Code, + string? Detail, + string TargetRoot, + string? SourceArchiveRoot = null, + string? Warning = null); + +/// +/// Moves one data root to another location. The copy lands in a staging directory on the target volume, the +/// stored paths are rewritten there, every file is compared against the source, and only then is the staging +/// directory renamed into place and the anchor written. The source directory is renamed, never deleted, so a +/// failed or interrupted move always leaves a complete old root behind. +/// +public sealed class DataRootMigrationEngine +{ + public const string StagingSuffix = ".migrating-"; + public const string SourceArchiveSuffix = ".migrated-"; + private const long HashComparisonLimitBytes = 4 * 1024 * 1024; + + private readonly string _appDirectory; + private readonly DataRootMigrationJournal _journal; + private readonly string _journalPath; + + public DataRootMigrationEngine(DataRootMigrationJournal journal, string journalPath, string appDirectory) + { + _journal = journal; + _journalPath = journalPath; + _appDirectory = appDirectory; + } + + public static string GetStagingPath(string targetRoot, string transactionId) + { + var suffix = transactionId[..Math.Min(8, transactionId.Length)]; + return Path.GetFullPath(Path.TrimEndingDirectorySeparator(targetRoot) + StagingSuffix + suffix); + } + + /// Checks a move before it starts; the migration window and the settings page both use this. + public static DataRootMigrationErrorCode Validate( + string? sourceRoot, + string? targetRoot, + string? appDirectory, + out string? detail) + { + detail = null; + + if (string.IsNullOrWhiteSpace(targetRoot)) + { + detail = "The target directory is empty."; + return DataRootMigrationErrorCode.TargetInvalid; + } + + string source; + string target; + try + { + source = string.IsNullOrWhiteSpace(sourceRoot) ? string.Empty : Path.GetFullPath(sourceRoot); + target = Path.GetFullPath(targetRoot); + } + catch (Exception exception) when (exception is ArgumentException or NotSupportedException or + PathTooLongException) + { + detail = exception.Message; + return DataRootMigrationErrorCode.TargetInvalid; + } + + if (File.Exists(target)) + { + detail = "The target path is an existing file."; + return DataRootMigrationErrorCode.TargetInvalid; + } + + if (source.Length > 0 && DataRootPaths.PathEquals(source, target)) + { + detail = "The target directory is the current data directory."; + return DataRootMigrationErrorCode.TargetEqualsSource; + } + + if (source.Length > 0 && DataRootPaths.IsSameOrNested(source, target)) + { + detail = "The target directory is inside the current data directory."; + return DataRootMigrationErrorCode.TargetInsideSource; + } + + if (source.Length > 0 && DataRootPaths.IsSameOrNested(target, source)) + { + detail = "The current data directory is inside the target directory."; + return DataRootMigrationErrorCode.SourceInsideTarget; + } + + if (!string.IsNullOrWhiteSpace(appDirectory) && DataRootPaths.IsSameOrNested(appDirectory, target)) + { + detail = "The target directory is inside the running application directory."; + return DataRootMigrationErrorCode.TargetInsideApp; + } + + if (Directory.Exists(target)) + { + try + { + if (Directory.EnumerateFileSystemEntries(target).Any()) + { + detail = "The target directory is not empty."; + return DataRootMigrationErrorCode.TargetNotEmpty; + } + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + detail = exception.Message; + return DataRootMigrationErrorCode.TargetNotWritable; + } + } + + var parent = Path.GetDirectoryName(target); + if (string.IsNullOrEmpty(parent)) + { + detail = "The target directory has no parent."; + return DataRootMigrationErrorCode.TargetInvalid; + } + + try + { + Directory.CreateDirectory(parent); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or + NotSupportedException) + { + detail = exception.Message; + return DataRootMigrationErrorCode.TargetNotWritable; + } + + if (!DataRootPaths.TryVerifyWritable(parent, out var writeError)) + { + detail = writeError; + return DataRootMigrationErrorCode.TargetNotWritable; + } + + return DataRootMigrationErrorCode.None; + } + + public DataRootMigrationResult Run( + IProgress? progress, + CancellationToken cancellationToken) + { + try + { + var validation = Validate(_journal.SourceRoot, _journal.TargetRoot, _appDirectory, out var validationDetail); + if (validation != DataRootMigrationErrorCode.None) + return Fail(progress, validation, validationDetail); + + if (string.IsNullOrWhiteSpace(_journal.AnchorPath)) + { + return Fail(progress, DataRootMigrationErrorCode.AnchorUnavailable, + "The migration does not know where to write the data-root anchor."); + } + + var target = Path.GetFullPath(_journal.TargetRoot); + var source = string.IsNullOrWhiteSpace(_journal.SourceRoot) + ? string.Empty + : Path.GetFullPath(_journal.SourceRoot); + var staging = _journal.StagingRoot is { Length: > 0 } recorded + ? Path.GetFullPath(recorded) + : GetStagingPath(target, _journal.TransactionId); + + _journal.StagingRoot = staging; + + // A previous run was interrupted after the staged copy had been moved into place. + if (_journal.State == DataRootMigrationState.Committing) + { + if (Directory.Exists(target)) + return FinishCommit(target, source, progress); + + if (Directory.Exists(staging)) + return Commit(staging, target, source, progress); + } + + progress?.Report(new DataRootMigrationProgress(DataRootMigrationPhase.Preparing, 0, 0, 0, 0, null)); + + if (!PrepareTarget(target, out var prepareError)) + return Fail(progress, prepareError, "The target directory could not be prepared."); + + if (Directory.Exists(staging)) + Directory.Delete(staging, true); + + var entries = EnumerateSource(source, out var sourceExists); + if (sourceExists && entries.Count == 0) + { + // Nothing to carry over (only caches and temporary files); the move is still meaningful. + } + + var totalBytes = entries.Sum(entry => entry.Length); + _journal.State = DataRootMigrationState.Copying; + Save(); + + if (entries.Count > 0) + { + Directory.CreateDirectory(staging); + CopyEntries(entries, staging, totalBytes, progress, cancellationToken); + } + else + { + Directory.CreateDirectory(staging); + } + + _journal.CopiedFileCount = entries.Count; + _journal.CopiedByteCount = totalBytes; + + _journal.State = DataRootMigrationState.Verifying; + Save(); + progress?.Report(new DataRootMigrationProgress(DataRootMigrationPhase.Verifying, entries.Count, + totalBytes, entries.Count, totalBytes, null)); + + var mismatch = Verify(entries, staging, source, cancellationToken); + if (mismatch is not null) + return Fail(progress, DataRootMigrationErrorCode.VerifyFailed, mismatch); + + var rewritten = DataRootPathRewriter.RewriteStaging(staging, source, target); + if (rewritten > 0) + _journal.ErrorMessage = null; + + return Commit(staging, target, source, progress); + } + catch (OperationCanceledException) + { + _journal.State = DataRootMigrationState.Cancelled; + Save(); + return new DataRootMigrationResult(false, DataRootMigrationErrorCode.Cancelled, null, + _journal.TargetRoot); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or + NotSupportedException) + { + return Fail(progress, DataRootMigrationErrorCode.CommitFailed, exception.Message); + } + } + + private bool PrepareTarget(string target, out DataRootMigrationErrorCode error) + { + error = DataRootMigrationErrorCode.None; + + try + { + Directory.CreateDirectory(Path.GetDirectoryName(target)!); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + error = DataRootMigrationErrorCode.TargetNotWritable; + return false; + } + + return true; + } + + private static List EnumerateSource(string source, out bool exists) + { + var entries = new List(); + if (source.Length == 0 || !Directory.Exists(source)) + { + exists = false; + return entries; + } + + exists = true; + foreach (var file in Directory.EnumerateFiles(source, "*", SearchOption.AllDirectories)) + { + var relative = Path.GetRelativePath(source, file); + if (ShouldSkip(relative)) + continue; + + long length; + try + { + length = new FileInfo(file).Length; + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + continue; + } + + entries.Add(new SourceEntry(file, relative, length)); + } + + return entries; + } + + private static bool ShouldSkip(string relativePath) + { + var normalized = relativePath.Replace('\\', '/'); + var segments = normalized.Split('/'); + + if (segments[0].StartsWith('.') || segments[0].StartsWith("updates", StringComparison.OrdinalIgnoreCase)) + return true; + + var fileName = segments[^1]; + if (fileName.EndsWith(".tmp", StringComparison.OrdinalIgnoreCase) || + fileName.EndsWith(".lock", StringComparison.OrdinalIgnoreCase)) + return true; + + return segments.Any(segment => segment.StartsWith(SourceArchiveSuffix.TrimStart('.') + "-", + StringComparison.OrdinalIgnoreCase)); + } + + private void CopyEntries( + IReadOnlyList entries, + string staging, + long totalBytes, + IProgress? progress, + CancellationToken cancellationToken) + { + var copiedBytes = 0L; + var copiedFiles = 0; + var stopwatch = Stopwatch.StartNew(); + + foreach (var entry in entries) + { + cancellationToken.ThrowIfCancellationRequested(); + + var destination = Path.Combine(staging, entry.RelativePath); + var directory = Path.GetDirectoryName(destination); + if (!string.IsNullOrEmpty(directory)) + Directory.CreateDirectory(directory); + + File.Copy(entry.SourcePath, destination, false); + try + { + File.SetLastWriteTimeUtc(destination, File.GetLastWriteTimeUtc(entry.SourcePath)); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + // Timestamps are only used to verify large files; a filesystem that refuses the setter still copies. + } + + copiedBytes += entry.Length; + copiedFiles++; + + if (stopwatch.ElapsedMilliseconds >= 150 || copiedFiles == entries.Count) + { + stopwatch.Restart(); + progress?.Report(new DataRootMigrationProgress(DataRootMigrationPhase.Copying, copiedFiles, + copiedBytes, entries.Count, totalBytes, entry.RelativePath)); + } + + _journal.CopiedFileCount = copiedFiles; + _journal.CopiedByteCount = copiedBytes; + if (copiedFiles % 200 == 0) + Save(); + } + + Save(); + } + + private static string? Verify( + IReadOnlyList entries, + string staging, + string source, + CancellationToken cancellationToken) + { + var mismatches = new List(); + + foreach (var entry in entries) + { + cancellationToken.ThrowIfCancellationRequested(); + + var copy = Path.Combine(staging, entry.RelativePath); + if (!File.Exists(copy)) + { + mismatches.Add($"{entry.RelativePath}: missing from the target copy"); + continue; + } + + var copyLength = new FileInfo(copy).Length; + if (copyLength != entry.Length) + { + mismatches.Add($"{entry.RelativePath}: expected {entry.Length} bytes, copied {copyLength}"); + continue; + } + + if (entry.Length <= HashComparisonLimitBytes) + { + if (!string.Equals(HashFile(entry.SourcePath), HashFile(copy), StringComparison.Ordinal)) + mismatches.Add($"{entry.RelativePath}: content hash differs"); + } + else + { + var sourceWrite = File.GetLastWriteTimeUtc(entry.SourcePath); + var copyWrite = File.GetLastWriteTimeUtc(copy); + if (sourceWrite != copyWrite) + mismatches.Add($"{entry.RelativePath}: last write time differs"); + } + + if (mismatches.Count >= 10) + break; + } + + return mismatches.Count == 0 ? null : string.Join(Environment.NewLine, mismatches); + } + + private static string HashFile(string path) + { + using var stream = File.OpenRead(path); + return Convert.ToHexString(SHA256.HashData(stream)); + } + + private DataRootMigrationResult Commit( + string staging, + string target, + string source, + IProgress? progress) + { + progress?.Report(new DataRootMigrationProgress(DataRootMigrationPhase.Committing, _journal.CopiedFileCount, + _journal.CopiedByteCount, _journal.CopiedFileCount, _journal.CopiedByteCount, null)); + + _journal.State = DataRootMigrationState.Committing; + Save(); + + try + { + if (!Directory.Exists(staging)) + return Fail(progress, DataRootMigrationErrorCode.CommitFailed, + "The staged copy disappeared before the move could be committed."); + + if (Directory.Exists(target)) + { + if (Directory.EnumerateFileSystemEntries(target).Any()) + return Fail(progress, DataRootMigrationErrorCode.TargetNotEmpty, null); + + Directory.Delete(target); + } + + Directory.Move(staging, target); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + return Fail(progress, DataRootMigrationErrorCode.CommitFailed, exception.Message); + } + + try + { + WriteAnchor(target); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or + NotSupportedException) + { + // The anchor write is the single commit point: without it the new location was never adopted, so put + // the staged copy back and leave the source untouched. + try + { + Directory.Move(target, staging); + } + catch (Exception restoreException) when (restoreException is IOException or UnauthorizedAccessException) + { + return Fail(progress, DataRootMigrationErrorCode.CommitFailed, + $"Anchor write failed ({exception.Message}) and the staged copy could not be restored " + + $"({restoreException.Message})."); + } + + return Fail(progress, DataRootMigrationErrorCode.AnchorUnavailable, exception.Message); + } + + return FinishCommit(target, source, progress); + } + + private DataRootMigrationResult FinishCommit( + string target, + string source, + IProgress? progress) + { + WriteAnchor(target); + + string? warning = null; + if (source.Length > 0 && Directory.Exists(source)) + { + var archivePath = BuildSourceArchivePath(source); + try + { + Directory.Move(source, archivePath); + _journal.SourceArchiveRoot = archivePath; + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + warning = $"The old data directory could not be renamed: {exception.Message}"; + } + } + + _journal.State = DataRootMigrationState.Completed; + Save(); + DataRootMigrationJournalStore.Delete(_journalPath); + + progress?.Report(new DataRootMigrationProgress(DataRootMigrationPhase.Completed, _journal.CopiedFileCount, + _journal.CopiedByteCount, _journal.CopiedFileCount, _journal.CopiedByteCount, null)); + + return new DataRootMigrationResult(true, DataRootMigrationErrorCode.None, null, target, + _journal.SourceArchiveRoot, warning); + } + + private void WriteAnchor(string target) + { + var anchorPath = _journal.AnchorPath!; + var directory = Path.GetDirectoryName(anchorPath); + if (!string.IsNullOrEmpty(directory)) + Directory.CreateDirectory(directory); + + DataRootAnchorStore.Write(anchorPath, new DataRootAnchor + { + Mode = _journal.Mode.ToStorageValue(), + DataRoot = target, + PackageKind = _journal.PackageKind, + UpdatedAtUtc = DateTimeOffset.UtcNow + }); + } + + private static string BuildSourceArchivePath(string source) + { + var trimmed = Path.TrimEndingDirectorySeparator(source); + var candidate = $"{trimmed}{SourceArchiveSuffix}{DateTime.Now:yyyyMMdd-HHmmss}"; + var index = 1; + while (Directory.Exists(candidate) || File.Exists(candidate)) + candidate = $"{trimmed}{SourceArchiveSuffix}{DateTime.Now:yyyyMMdd-HHmmss}-{index++}"; + + return candidate; + } + + private void Save() + { + DataRootMigrationJournalStore.Write(_journalPath, _journal); + } + + private DataRootMigrationResult Fail( + IProgress? progress, + DataRootMigrationErrorCode code, + string? detail) + { + _journal.State = DataRootMigrationState.Failed; + _journal.ErrorMessage = detail; + Save(); + + progress?.Report(new DataRootMigrationProgress(DataRootMigrationPhase.Failed, _journal.CopiedFileCount, + _journal.CopiedByteCount, _journal.CopiedFileCount, _journal.CopiedByteCount, null)); + + return new DataRootMigrationResult(false, code, detail, _journal.TargetRoot); + } + + private sealed record SourceEntry(string SourcePath, string RelativePath, long Length); +} \ No newline at end of file diff --git a/SecRandom.Core/Services/DataRoot/DataRootMigrationJournal.cs b/SecRandom.Core/Services/DataRoot/DataRootMigrationJournal.cs new file mode 100644 index 000000000..fc9d026cf --- /dev/null +++ b/SecRandom.Core/Services/DataRoot/DataRootMigrationJournal.cs @@ -0,0 +1,123 @@ +using System.Text.Json; +using System.Text.Json.Serialization; +using SecRandom.Shared.DataRoot; + +namespace SecRandom.Core.Services.DataRoot; + +/// +/// Durable state of one data-root move. The journal lives beside the anchor (package root for a portable +/// package, the per-user anchor directory otherwise), never inside either data root, so a half-finished move can +/// always be recognised on the next start and the old directory is never deleted by the migration itself. +/// +public sealed class DataRootMigrationJournal +{ + public const int CurrentSchemaVersion = 1; + + public int SchemaVersion { get; set; } = CurrentSchemaVersion; + + public string TransactionId { get; set; } = string.Empty; + + public DataRootMigrationState State { get; set; } = DataRootMigrationState.Pending; + + public string SourceRoot { get; set; } = string.Empty; + + public string TargetRoot { get; set; } = string.Empty; + + public string? StagingRoot { get; set; } + + public string? SourceArchiveRoot { get; set; } + + public DataRootMode Mode { get; set; } = DataRootMode.Custom; + + public string? PackageKind { get; set; } + + public string? AnchorPath { get; set; } + + public string? ErrorMessage { get; set; } + + public int CopiedFileCount { get; set; } + + public long CopiedByteCount { get; set; } + + public DateTimeOffset CreatedAtUtc { get; set; } = DateTimeOffset.UtcNow; + + public DateTimeOffset UpdatedAtUtc { get; set; } = DateTimeOffset.UtcNow; +} + +public enum DataRootMigrationState +{ + Pending = 0, + Copying = 1, + Verifying = 2, + Committing = 3, + Completed = 4, + Failed = 5, + Cancelled = 6 +} + +public static class DataRootMigrationJournalStore +{ + private static readonly JsonSerializerOptions JsonOptions = new() + { + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + WriteIndented = true, + Converters = { new JsonStringEnumConverter() } + }; + + public static string GetPath(string anchorDirectory) + { + return Path.Combine(anchorDirectory, DataRootPaths.JournalFileName); + } + + public static DataRootMigrationJournal? Read(string journalPath) + { + try + { + if (!File.Exists(journalPath)) + return null; + + var journal = JsonSerializer.Deserialize( + File.ReadAllText(journalPath), JsonOptions); + if (journal is null || journal.SchemaVersion != DataRootMigrationJournal.CurrentSchemaVersion) + return null; + + return journal; + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or + JsonException or NotSupportedException) + { + return null; + } + } + + public static void Write(string journalPath, DataRootMigrationJournal journal) + { + journal.UpdatedAtUtc = DateTimeOffset.UtcNow; + + var directory = Path.GetDirectoryName(journalPath); + if (!string.IsNullOrEmpty(directory)) + Directory.CreateDirectory(directory); + + var temporaryPath = journalPath + ".tmp"; + using (var stream = new FileStream(temporaryPath, FileMode.Create, FileAccess.Write, FileShare.None)) + { + JsonSerializer.Serialize(stream, journal, JsonOptions); + stream.Flush(true); + } + + File.Move(temporaryPath, journalPath, true); + } + + public static void Delete(string journalPath) + { + try + { + if (File.Exists(journalPath)) + File.Delete(journalPath); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + // A journal that cannot be deleted is harmless once its transaction is completed. + } + } +} \ No newline at end of file diff --git a/SecRandom.Core/Services/DataRoot/DataRootPathRewriter.cs b/SecRandom.Core/Services/DataRoot/DataRootPathRewriter.cs new file mode 100644 index 000000000..2c6eca5cd --- /dev/null +++ b/SecRandom.Core/Services/DataRoot/DataRootPathRewriter.cs @@ -0,0 +1,176 @@ +using System.Text.Json; +using System.Text.Json.Nodes; +using SecRandom.Shared.DataRoot; + +namespace SecRandom.Core.Services.DataRoot; + +/// +/// Rewrites the data files that may carry an absolute path from the old data root. Only two shapes exist today: +/// attached draw-image settings under list/ (ImagePath) and the proof attestation queue +/// (path). Values that live outside the old root — a user-picked external image, a URL — are left +/// byte-identical, because the migration must never claim to know what they meant. +/// +public static class DataRootPathRewriter +{ + private static readonly JsonSerializerOptions CompactWriteOptions = new() + { + WriteIndented = false + }; + + private static readonly JsonSerializerOptions IndentedWriteOptions = new() + { + WriteIndented = true + }; + + private static readonly JsonNodeOptions NodeOptions = new() + { + PropertyNameCaseInsensitive = false + }; + + /// Rewrites every rewritable file inside the staging copy and returns how many values changed. + public static int RewriteStaging(string stagingRoot, string oldRoot, string newRoot) + { + var changed = 0; + + var listDirectory = Path.Combine(stagingRoot, "list"); + if (Directory.Exists(listDirectory)) + { + foreach (var file in Directory.EnumerateFiles(listDirectory, "*.json", SearchOption.AllDirectories)) + changed += RewriteFile(file, oldRoot, newRoot, imageOnly: true); + } + + var attestationQueue = Path.Combine(stagingRoot, "proofs", "attestation-queue.json"); + if (File.Exists(attestationQueue)) + changed += RewriteFile(attestationQueue, oldRoot, newRoot, imageOnly: false); + + return changed; + } + + private static int RewriteFile(string file, string oldRoot, string newRoot, bool imageOnly) + { + string original; + try + { + original = File.ReadAllText(file); + } + catch (IOException) + { + return 0; + } + + JsonNode? root; + try + { + root = JsonNode.Parse(original, NodeOptions); + } + catch (JsonException) + { + return 0; + } + + if (root is null) + return 0; + + var changed = RewriteNode(root, oldRoot, newRoot, imageOnly); + if (changed == 0) + return 0; + + // Keep the file's existing formatting: a compact settings file must stay compact, and an indented one + // must not be flattened, otherwise the migration would produce a spurious whole-file diff. + var writeOptions = original.Contains('\n') ? IndentedWriteOptions : CompactWriteOptions; + File.WriteAllText(file, root.ToJsonString(writeOptions)); + return changed; + } + + private static int RewriteNode(JsonNode? node, string oldRoot, string newRoot, bool imageOnly) + { + var changed = 0; + + switch (node) + { + case JsonObject jsonObject: + foreach (var property in jsonObject.ToList()) + { + if (Matches(property.Key, imageOnly) && + TryReadString(property.Value, out var text) && + RewriteValue(text, oldRoot, newRoot) is var rewritten && + !string.Equals(rewritten, text, StringComparison.Ordinal)) + { + jsonObject[property.Key] = rewritten; + changed++; + continue; + } + + changed += RewriteNode(property.Value, oldRoot, newRoot, imageOnly); + } + + break; + + case JsonArray jsonArray: + for (var index = 0; index < jsonArray.Count; index++) + { + var item = jsonArray[index]; + if (TryReadString(item, out var text) && + RewriteValue(text, oldRoot, newRoot) is var rewritten && + !string.Equals(rewritten, text, StringComparison.Ordinal)) + { + jsonArray[index] = rewritten; + changed++; + continue; + } + + changed += RewriteNode(item, oldRoot, newRoot, imageOnly); + } + + break; + } + + return changed; + } + + private static bool Matches(string propertyName, bool imageOnly) + { + if (string.Equals(propertyName, "ImagePath", StringComparison.OrdinalIgnoreCase)) + return true; + + if (imageOnly) + return false; + + return string.Equals(propertyName, "path", StringComparison.OrdinalIgnoreCase) || + string.Equals(propertyName, "proofPath", StringComparison.OrdinalIgnoreCase); + } + + private static bool TryReadString(JsonNode? node, out string text) + { + text = string.Empty; + if (node is not JsonValue value || !value.TryGetValue(out var parsed) || parsed is null) + return false; + + text = parsed; + return true; + } + + private static string RewriteValue(string value, string oldRoot, string newRoot) + { + if (string.IsNullOrWhiteSpace(value) || DataPathReference.IsStoredRelative(value)) + return value; + + string fullPath; + try + { + fullPath = Path.GetFullPath(value.Trim()); + } + catch (Exception exception) when (exception is ArgumentException or NotSupportedException or + PathTooLongException) + { + return value; + } + + if (!DataRootPaths.IsSameOrNested(oldRoot, fullPath)) + return value; + + var relative = Path.GetRelativePath(oldRoot, fullPath); + return relative.Replace(Path.DirectorySeparatorChar, '/') + .Replace(Path.AltDirectorySeparatorChar, '/'); + } +} \ No newline at end of file diff --git a/SecRandom.Desktop/Program.cs b/SecRandom.Desktop/Program.cs index 6d66bbfa4..31a7c24f1 100644 --- a/SecRandom.Desktop/Program.cs +++ b/SecRandom.Desktop/Program.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.IO; using System.Reflection; @@ -13,6 +13,7 @@ using SecRandom.Services.Plugins; using SecRandom.Platforms; using SecRandom.Shared; +using SecRandom.Shared.DataRoot; #if SEC_RANDOM_PLATFORM_WINDOWS using SecRandom.Platforms.Windows; #elif SEC_RANDOM_PLATFORM_LINUX @@ -33,15 +34,44 @@ public static void Main(string[] args) { // 版本元数据由头程序集承载;显式发布可让桌面端与移动头共用同一条解析路径 GlobalConstants.SetVersionAssembly(typeof(Program).Assembly); - // UiAccess startup reads the persisted topmost setting, so data-root selection must precede it. - Utils.PrepareDesktopDataRoot(); - if (!UiAccessStartup.ShouldContinue(args)) + + var dataRootLaunch = DataRootCommandLine.Parse(args); + if (dataRootLaunch.Error is { } dataRootLaunchError) { - Environment.ExitCode = UiAccessStartup.BootstrapExitCode; + Console.Error.WriteLine(dataRootLaunchError); + Environment.ExitCode = 2; return; } - args = UiAccessStartup.GetApplicationArguments(args); + DataRootLaunchState.MigrationId = dataRootLaunch.MigrationId; + if (dataRootLaunch.IsMigration) + { + // A data-root migration owns its own window and must not open the normal app, so no root is + // prepared and no persisted setting is read before the migration has finished. + args = [.. dataRootLaunch.PassThroughArguments]; + } + else + { + // UiAccess startup reads the persisted topmost setting, so data-root selection must precede it. + var dataRootPreparation = Utils.PrepareDesktopDataRoot( + GlobalConstants.IsDevelopment, + dataRootLaunch.DataRoot); + if (!string.IsNullOrWhiteSpace(dataRootLaunch.DataRoot)) + { + // A relaunch (UiAccess replacement or crash recovery) must inherit the same explicit root. + Environment.SetEnvironmentVariable(Utils.DataRootEnvironmentVariable, dataRootPreparation.DataRoot); + } + + args = [.. dataRootLaunch.PassThroughArguments]; + if (!UiAccessStartup.ShouldContinue(args)) + { + Environment.ExitCode = UiAccessStartup.BootstrapExitCode; + return; + } + + args = UiAccessStartup.GetApplicationArguments(args); + } + ConfigurePlatformServices(); ProtocolActivation.SetStartupArguments(args); CrashRecoveryRuntime.SetStartupArguments(args); diff --git a/SecRandom.Shared/AGENTS.md b/SecRandom.Shared/AGENTS.md index 8fedfe452..ca81c14cc 100644 --- a/SecRandom.Shared/AGENTS.md +++ b/SecRandom.Shared/AGENTS.md @@ -113,8 +113,9 @@ Keep this map short and stable. When code moves, AI agents should re-read the mo - `ConfigBase` / `ProfileConfigBase` define paths and identity for persisted files; handlers and desktop storage live outside Shared. - Profile list/history paths validate `Name` through `ProfileConfigBase` before resolving a file path: only a portable single file name is accepted, with Windows reserved-name/invalid-character rules applied on every platform. Empty names remain valid model construction defaults, not valid persistence paths; never sanitize or rewrite a supplied name. -- `Utils.GetFilePath(...)` is the expected route for data/config paths. Its default desktop/portable root remains `/data`. `Utils.ConfigureMobileDataRoot()` is a startup-only Android/iOS operation with a fixed `LocalApplicationData/SecRandom/data` target; shared `SecRandom.App` calls it exactly once in its mobile branch before any path is read. No Shared model, Core service, plugin, or desktop flow may change the root. Accessing `data/config` also applies filesystem hiding: Windows uses `Hidden|System`, while Unix-like hosts maintain the parent `.hidden` entry because the stable `config` name cannot be changed. -- Desktop `Utils.PrepareDesktopDataRoot()` performs a real temporary-file write probe before the first data path is resolved. Installed package kinds fall back to `LocalApplicationData/SecRandom/data` when the package directory is not writable; `portable-zip` keeps the package-root data contract and returns a failure result for the app layer to present before Host startup. +- `Utils.GetFilePath(...)` is the expected route for data/config paths. The desktop root is resolved by `DataRoot/DesktopDataRootResolver` with a fixed precedence (`--data-root` > `SECRANDOM_DATA_ROOT` > anchor `data-root.json` > legacy-location adoption > mode default): portable packages get `/data`, installed packages get a per-user standard root, and a user's chosen root is a `Custom` anchor mode. `Utils.ConfigureMobileDataRoot()` is a startup-only Android/iOS operation with a fixed `LocalApplicationData/SecRandom/data` target; shared `SecRandom.App` calls it exactly once in its mobile branch before any path is read. No Shared model, Core service, plugin, or desktop flow may change the root. Accessing `data/config` also applies filesystem hiding: Windows uses `Hidden|System`, while Unix-like hosts maintain the parent `.hidden` entry because the stable `config` name cannot be changed. +- Desktop `Utils.PrepareDesktopDataRoot(bool isDevelopmentBuild, string? commandLineDataRoot)` performs a real temporary-file write probe before the first data path is resolved and records `Mode`/`Source`/`AnchorPath`/`OtherDataRoots`/`NeedsMigrationNotice` on its result. Installed builds never treat the install directory as the default root, a payload-resident legacy `data/` directory is moved to the package root, and any unwritable root returns a failure result the app presents before Host startup. The anchor is only written for default/legacy/adopted locations, not for a command-line/env override and not for development builds already on the package directory. +- Paths persisted inside data files must stay root-relative: use `DataPathReference.ToStored(path, Utils.DataRoot)` when writing an attached draw image (`ImagePath`) or an attestation-queue `Path`, and `DataPathReference.Resolve` when reading. Rooted values are also accepted on read so a file written by an older build keeps working, and the migration rewrites them. - `Utils.LauncherFileName` / `Utils.TryGetPortableLauncherPath(out ...)` resolve the stable `SecRandomLauncher` at the portable package root; the resolution only succeeds for the documented layout (an `app-*` directory whose marker says `portable-zip` plus an existing launcher beside it). Anything meant to outlive the running build — autostart entries, `secrandom://` registration — must use it instead of a path inside the activated payload, which an update replaces; in-app restart and crash recovery must not, because they relaunch the build that is already running. - If adding a shared model that will be persisted, consider backward-compatible defaults and nullable behavior first. - Comments should document serialization/backward-compatibility constraints, not obvious property names. diff --git a/SecRandom.Shared/DataRoot/DataPathReference.cs b/SecRandom.Shared/DataRoot/DataPathReference.cs new file mode 100644 index 000000000..d632fd170 --- /dev/null +++ b/SecRandom.Shared/DataRoot/DataPathReference.cs @@ -0,0 +1,81 @@ +namespace SecRandom.Shared.DataRoot; + +/// +/// Converts a path persisted inside a data file between the absolute form older builds wrote and the +/// data-root-relative form this build writes. Relative values survive a data-root move; absolute values keep +/// working exactly as before, so a migration never has to guess what an external path meant. +/// +public static class DataPathReference +{ + /// + /// True when the stored value is meant to be resolved against the current data root. URLs and rooted paths + /// are explicitly not: they are self-contained or deliberately outside the data root. + /// + public static bool IsStoredRelative(string? value) + { + if (string.IsNullOrWhiteSpace(value)) + return false; + + var trimmed = value.Trim(); + if (trimmed.Contains("://", StringComparison.Ordinal)) + return false; + + return !Path.IsPathRooted(trimmed) && !trimmed.StartsWith('~'); + } + + /// + /// Stores relative to when it lives inside it, + /// and otherwise keeps the original value untouched (an external or shared path must not be rewritten). + /// + public static string ToStored(string? absolutePath, string dataRoot) + { + if (string.IsNullOrWhiteSpace(absolutePath) || string.IsNullOrWhiteSpace(dataRoot)) + return absolutePath ?? string.Empty; + + var value = absolutePath.Trim(); + if (IsStoredRelative(value)) + return value; + + string fullPath; + string fullRoot; + try + { + fullPath = Path.GetFullPath(value); + fullRoot = Path.GetFullPath(dataRoot); + } + catch (Exception exception) when (exception is ArgumentException or NotSupportedException or + PathTooLongException) + { + return value; + } + + if (!DataRootPaths.IsSameOrNested(fullRoot, fullPath)) + return value; + + var relative = Path.GetRelativePath(fullRoot, fullPath); + return relative.Replace(Path.DirectorySeparatorChar, '/') + .Replace(Path.AltDirectorySeparatorChar, '/'); + } + + /// Resolves a stored value against the current data root; absolute values are returned unchanged. + public static string Resolve(string? storedPath, string dataRoot) + { + if (string.IsNullOrWhiteSpace(storedPath)) + return storedPath ?? string.Empty; + + var value = storedPath.Trim(); + if (!IsStoredRelative(value) || string.IsNullOrWhiteSpace(dataRoot)) + return value; + + return Path.GetFullPath(Path.Combine(dataRoot, value.Replace('/', Path.DirectorySeparatorChar))); + } + + /// True when the two stored values point at the same entry, allowing relative and absolute forms. + public static bool RefersToSame(string? left, string? right, string dataRoot) + { + return string.Equals( + Resolve(left, dataRoot).Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar), + Resolve(right, dataRoot).Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar), + DataRootPaths.PathComparison); + } +} \ No newline at end of file diff --git a/SecRandom.Shared/DataRoot/DataRootAnchorStore.cs b/SecRandom.Shared/DataRoot/DataRootAnchorStore.cs new file mode 100644 index 000000000..9afe2d707 --- /dev/null +++ b/SecRandom.Shared/DataRoot/DataRootAnchorStore.cs @@ -0,0 +1,99 @@ +using System.Text.Json; + +namespace SecRandom.Shared.DataRoot; + +/// +/// Read/write the data-root anchor. The file is tiny, device-local, and must never be part of an archive, +/// so it is written with the same temp-file + atomic replace pattern the config handlers use. +/// +public static class DataRootAnchorStore +{ + private static readonly JsonSerializerOptions JsonOptions = new() + { + WriteIndented = true, + PropertyNamingPolicy = JsonNamingPolicy.CamelCase + }; + + public static DataRootAnchorReadResult Read(string anchorPath) + { + if (string.IsNullOrWhiteSpace(anchorPath) || !File.Exists(anchorPath)) + return new DataRootAnchorReadResult(DataRootAnchorStatus.Missing, null, null); + + try + { + var anchor = JsonSerializer.Deserialize(File.ReadAllText(anchorPath), JsonOptions); + if (anchor is null) + return new DataRootAnchorReadResult(DataRootAnchorStatus.Invalid, null, "The anchor file is empty."); + + if (anchor.SchemaVersion is < 1 or > DataRootAnchor.CurrentSchemaVersion) + return new DataRootAnchorReadResult( + DataRootAnchorStatus.Invalid, + null, + $"Unsupported data-root anchor schema version {anchor.SchemaVersion}."); + + if (string.IsNullOrWhiteSpace(anchor.DataRoot)) + return new DataRootAnchorReadResult( + DataRootAnchorStatus.Invalid, + null, + "The anchor file does not name a data root."); + + anchor.DataRoot = Path.TrimEndingDirectorySeparator(Path.GetFullPath(anchor.DataRoot)); + anchor.Mode = DataRootModeExtensions.Parse(anchor.Mode).ToStorageValue(); + return new DataRootAnchorReadResult(DataRootAnchorStatus.Valid, anchor, null); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException + or JsonException or NotSupportedException or ArgumentException) + { + return new DataRootAnchorReadResult( + DataRootAnchorStatus.Invalid, + null, + $"The data-root anchor could not be read: {exception.Message}"); + } + } + + public static void Write(string anchorPath, DataRootAnchor anchor) + { + ArgumentException.ThrowIfNullOrWhiteSpace(anchorPath); + ArgumentNullException.ThrowIfNull(anchor); + + anchor.SchemaVersion = DataRootAnchor.CurrentSchemaVersion; + anchor.UpdatedAtUtc = DateTimeOffset.UtcNow; + + var directory = Path.GetDirectoryName(Path.GetFullPath(anchorPath)); + if (!string.IsNullOrEmpty(directory)) + Directory.CreateDirectory(directory); + + var temporaryPath = anchorPath + ".tmp"; + var json = JsonSerializer.Serialize(anchor, JsonOptions); + using (var stream = new FileStream(temporaryPath, FileMode.Create, FileAccess.Write, FileShare.None)) + { + var bytes = System.Text.Encoding.UTF8.GetBytes(json); + stream.Write(bytes, 0, bytes.Length); + stream.Flush(true); + } + + File.Move(temporaryPath, anchorPath, overwrite: true); + } + + /// Writes the anchor for a resolved root unless the resolution came from an explicit override. + public static void TryPersist(DesktopDataRootResolution resolution, bool write) + { + if (!write || string.IsNullOrWhiteSpace(resolution.AnchorPath)) + return; + + try + { + Write(resolution.AnchorPath, new DataRootAnchor + { + Mode = resolution.Mode.ToStorageValue(), + DataRoot = resolution.DataRoot, + PackageKind = resolution.PackageKind + }); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException + or NotSupportedException or ArgumentException) + { + // Persisting the anchor is best effort: the resolved root still works for this run. + } + } +} \ No newline at end of file diff --git a/SecRandom.Shared/DataRoot/DataRootCommandLine.cs b/SecRandom.Shared/DataRoot/DataRootCommandLine.cs new file mode 100644 index 000000000..840c32968 --- /dev/null +++ b/SecRandom.Shared/DataRoot/DataRootCommandLine.cs @@ -0,0 +1,101 @@ +namespace SecRandom.Shared.DataRoot; + +/// +/// Parses the desktop launch options that select or migrate the data root. Both options are stripped from the +/// arguments the rest of the app sees, because Avalonia, crash recovery, and plugins must never interpret them. +/// +public sealed class DataRootLaunchArguments +{ + public const string DataRootOption = "--data-root"; + public const string MigrationOption = "--data-root-migration"; + + /// Value of --data-root, if the launch carried one. + public string? DataRoot { get; init; } + + /// Migration transaction id of --data-root-migration, if the launch carries one. + public Guid? MigrationId { get; init; } + + /// Arguments with the data-root options removed, in their original order. + public IReadOnlyList PassThroughArguments { get; init; } = []; + + /// A malformed option value; startup reports it instead of silently ignoring the request. + public string? Error { get; init; } + + public bool IsMigration => MigrationId is not null; +} + +public static class DataRootCommandLine +{ + public static DataRootLaunchArguments Parse(IReadOnlyList? arguments) + { + if (arguments is null || arguments.Count == 0) + return new DataRootLaunchArguments { PassThroughArguments = [] }; + + string? dataRoot = null; + string? migrationValue = null; + string? error = null; + var remaining = new List(arguments.Count); + + for (var index = 0; index < arguments.Count; index++) + { + var argument = arguments[index]; + + if (TryReadOption(argument, DataRootLaunchArguments.DataRootOption, arguments, ref index, out var value)) + { + if (string.IsNullOrWhiteSpace(value)) + error ??= $"{DataRootLaunchArguments.DataRootOption} requires a directory."; + else + dataRoot = value; + continue; + } + + if (TryReadOption(argument, DataRootLaunchArguments.MigrationOption, arguments, ref index, out var migrationText)) + { + if (Guid.TryParse(migrationText, out var migrationId)) + migrationValue = migrationId.ToString("N"); + else + error ??= $"{DataRootLaunchArguments.MigrationOption} requires a migration transaction id."; + continue; + } + + remaining.Add(argument); + } + + return new DataRootLaunchArguments + { + DataRoot = string.IsNullOrWhiteSpace(dataRoot) ? null : dataRoot, + MigrationId = migrationValue is null ? null : Guid.ParseExact(migrationValue, "N"), + PassThroughArguments = remaining, + Error = error + }; + } + + /// Writes the resolved custom root to the child-process environment so a relaunch keeps the same root. + public const string DataRootEnvironmentVariable = "SECRANDOM_DATA_ROOT"; + + private static bool TryReadOption( + string argument, + string option, + IReadOnlyList arguments, + ref int index, + out string? value) + { + value = null; + + if (string.Equals(argument, option, StringComparison.Ordinal)) + { + if (index + 1 >= arguments.Count) + return true; + + value = arguments[++index]; + return true; + } + + var prefix = option + "="; + if (!argument.StartsWith(prefix, StringComparison.Ordinal)) + return false; + + value = argument[prefix.Length..]; + return true; + } +} \ No newline at end of file diff --git a/SecRandom.Shared/DataRoot/DataRootLaunchState.cs b/SecRandom.Shared/DataRoot/DataRootLaunchState.cs new file mode 100644 index 000000000..7ccfe5bd7 --- /dev/null +++ b/SecRandom.Shared/DataRoot/DataRootLaunchState.cs @@ -0,0 +1,13 @@ +namespace SecRandom.Shared.DataRoot; + +/// +/// Migration hand-off between the process entry point and the Avalonia application. The entry point parses +/// --data-root-migration before Avalonia exists; the app then draws the migration window instead of the +/// normal shell. Nothing else may set this: a normal launch must never enter migration mode by accident. +/// +public static class DataRootLaunchState +{ + public static Guid? MigrationId { get; set; } + + public static bool IsMigration => MigrationId is not null; +} \ No newline at end of file diff --git a/SecRandom.Shared/DataRoot/DataRootPaths.cs b/SecRandom.Shared/DataRoot/DataRootPaths.cs new file mode 100644 index 000000000..191fa07e0 --- /dev/null +++ b/SecRandom.Shared/DataRoot/DataRootPaths.cs @@ -0,0 +1,235 @@ +using System.Runtime.InteropServices; + +namespace SecRandom.Shared.DataRoot; + +/// +/// Platform paths the data-root layer needs. These are pure path computations; nothing here creates a +/// directory or touches the file system. +/// +public static class DataRootPaths +{ + public const string AnchorFileName = "data-root.json"; + public const string JournalFileName = "data-root-journal.json"; + public const string MigrationLockFileName = "data-root-migration.lock"; + public const string PayloadMarkerFileName = "SecRandom.package.json"; + public const string PayloadDirectoryPrefix = "app-"; + public const string DataDirectoryName = "data"; + public const string ProductDirectoryName = "SecRandom"; + + /// Per-user application data root the standard mode creates. + public static string GetStandardDataRoot() + { + return Path.Combine(GetStandardAnchorDirectory(), DataDirectoryName); + } + + /// Per-user directory that holds the anchor, journal, and migration lock for installed builds. + public static string GetStandardAnchorDirectory() + { + if (OperatingSystem.IsWindows()) + { + var localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); + if (!string.IsNullOrWhiteSpace(localAppData)) + return Path.Combine(localAppData, ProductDirectoryName); + + var home = GetHomeDirectory(); + return Path.Combine(home, "AppData", "Local", ProductDirectoryName); + } + + if (OperatingSystem.IsMacOS()) + return Path.Combine(GetHomeDirectory(), "Library", "Application Support", ProductDirectoryName); + + var configHome = Environment.GetEnvironmentVariable("XDG_CONFIG_HOME"); + return string.IsNullOrWhiteSpace(configHome) + ? Path.Combine(GetHomeDirectory(), ".config", "secrandom") + : Path.Combine(configHome, "secrandom"); + } + + /// Anchor file path: inside the portable package so it travels with the folder, else per-user. + public static string GetAnchorPath(string packageRoot, bool isPortablePackage) + { + return Path.Combine(GetAnchorDirectory(packageRoot, isPortablePackage), AnchorFileName); + } + + public static string GetJournalPath(string packageRoot, bool isPortablePackage) + { + return Path.Combine(GetAnchorDirectory(packageRoot, isPortablePackage), JournalFileName); + } + + public static string GetMigrationLockPath(string packageRoot, bool isPortablePackage) + { + return Path.Combine(GetAnchorDirectory(packageRoot, isPortablePackage), MigrationLockFileName); + } + + public static string GetAnchorDirectory(string packageRoot, bool isPortablePackage) + { + return isPortablePackage ? Path.GetFullPath(packageRoot) : GetStandardAnchorDirectory(); + } + + public static string GetHomeDirectory() + { + var home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); + if (!string.IsNullOrWhiteSpace(home)) + return home; + + var env = Environment.GetEnvironmentVariable("HOME"); + return string.IsNullOrWhiteSpace(env) ? Path.GetTempPath() : env; + } + + /// Case sensitivity matches the filesystem convention of the running platform. + public static StringComparison PathComparison => + OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; + + public static bool PathEquals(string left, string right) + { + return string.Equals( + Path.TrimEndingDirectorySeparator(Path.GetFullPath(left)), + Path.TrimEndingDirectorySeparator(Path.GetFullPath(right)), + PathComparison); + } + + /// True when equals or lives underneath it. + public static bool IsSameOrNested(string parent, string candidate) + { + var normalizedParent = Path.TrimEndingDirectorySeparator(Path.GetFullPath(parent)); + var normalizedCandidate = Path.TrimEndingDirectorySeparator(Path.GetFullPath(candidate)); + if (string.Equals(normalizedParent, normalizedCandidate, PathComparison)) + return true; + + return normalizedCandidate.StartsWith( + normalizedParent + Path.DirectorySeparatorChar, + PathComparison); + } + + /// Whether this process runs from a portable package payload (used before the resolver runs). + public static bool IsPortablePackageLayout(string packageRoot, string appDirectory) + { + if (string.IsNullOrWhiteSpace(packageRoot) || !Directory.Exists(packageRoot)) + return false; + + var normalizedAppDirectory = Path.GetFullPath(appDirectory); + var parent = Directory.GetParent(normalizedAppDirectory)?.FullName; + if (parent is null || !PathEquals(packageRoot, parent)) + return false; + + var appDirectoryName = Path.GetFileName(normalizedAppDirectory.TrimEnd(Path.DirectorySeparatorChar)); + return appDirectoryName.StartsWith(PayloadDirectoryPrefix, StringComparison.Ordinal) + && File.Exists(Path.Combine(normalizedAppDirectory, PayloadMarkerFileName)); + } + + /// Reads the package marker's packageKind, ignoring every malformed or missing marker. + public static string? ReadPackageKind(string? payloadDirectory) + { + if (string.IsNullOrWhiteSpace(payloadDirectory)) + return null; + + var markerPath = Path.Combine(payloadDirectory, PayloadMarkerFileName); + try + { + if (!File.Exists(markerPath)) + return null; + + using var document = System.Text.Json.JsonDocument.Parse(File.ReadAllText(markerPath)); + return document.RootElement.TryGetProperty("packageKind", out var kind) + ? kind.GetString() + : null; + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException + or System.Text.Json.JsonException or NotSupportedException) + { + return null; + } + } + + public static bool IsPortablePackageKind(string? packageKind) + { + return string.Equals(packageKind, "portable-zip", StringComparison.Ordinal); + } + + /// Enumerates payload directories beside the package root (app-*). + public static IReadOnlyList EnumeratePayloadDirectories(string packageRoot) + { + try + { + if (!Directory.Exists(packageRoot)) + return []; + + return Directory.EnumerateDirectories(packageRoot, PayloadDirectoryPrefix + "*") + .Where(directory => File.Exists(Path.Combine(directory, PayloadMarkerFileName))) + .OrderBy(directory => directory, StringComparer.Ordinal) + .Select(Path.GetFullPath) + .ToArray(); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException + or DirectoryNotFoundException) + { + return []; + } + } + + /// True when the directory exists and holds at least one entry. + public static bool HasData(string? directory) + { + if (string.IsNullOrWhiteSpace(directory) || !Directory.Exists(directory)) + return false; + + try + { + return Directory.EnumerateFileSystemEntries(directory).Any(); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + return false; + } + } + + /// Real write probe used before a root is accepted. + public static bool TryVerifyWritable(string directory, out string? errorMessage) + { + var testFile = Path.Combine(directory, $".secrandom-write-test-{Guid.NewGuid():N}.tmp"); + try + { + Directory.CreateDirectory(directory); + using (var stream = new FileStream(testFile, FileMode.CreateNew, FileAccess.Write, FileShare.None)) + { + stream.WriteByte(0); + stream.Flush(true); + } + + File.Delete(testFile); + errorMessage = null; + return true; + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or + NotSupportedException or ArgumentException) + { + TryDeleteFile(testFile); + errorMessage = exception.Message; + return false; + } + } + + public static void TryDeleteFile(string path) + { + try + { + if (File.Exists(path)) + File.Delete(path); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + // Best effort: the caller's original error is more useful. + } + } + + /// Maps a directory onto the path separator style of the current platform. + public static string Normalize(string path) + { + return Path.TrimEndingDirectorySeparator(Path.GetFullPath(path)); + } + + internal static bool IsWindows => OperatingSystem.IsWindows(); + + internal static bool IsMacOs => OperatingSystem.IsMacOS(); + + internal static bool IsLinux => RuntimeInformation.IsOSPlatform(OSPlatform.Linux); +} \ No newline at end of file diff --git a/SecRandom.Shared/DataRoot/DataRootTypes.cs b/SecRandom.Shared/DataRoot/DataRootTypes.cs new file mode 100644 index 000000000..29c144a95 --- /dev/null +++ b/SecRandom.Shared/DataRoot/DataRootTypes.cs @@ -0,0 +1,167 @@ +namespace SecRandom.Shared.DataRoot; + +/// +/// Where the desktop data root is expected to live. The mode is persisted in the anchor file so a later +/// start does not have to re-derive it from the package layout. +/// +public enum DataRootMode +{ + /// Data lives beside the portable payload (<package root>/data). + Package = 0, + + /// Data lives in the platform per-user application data directory. + Standard = 1, + + /// Data lives wherever the user picked. + Custom = 2 +} + +/// Why this process ended up with the data root it has; shown in diagnostics and the storage page. +public enum DataRootSource +{ + Unknown = 0, + + /// A --data-root command-line argument won. + CommandLine = 1, + + /// The SECRANDOM_DATA_ROOT environment variable won. + Environment = 2, + + /// The persisted anchor file won. + Anchor = 3, + + /// An older data location was found and claimed, because the new default was empty. + Legacy = 4, + + /// Data was found inside a versioned payload directory and folded back out before use. + RepairedPayload = 5, + + /// The mode default was used and no older data existed. + ModeDefault = 6 +} + +public static class DataRootModeExtensions +{ + public static string ToStorageValue(this DataRootMode mode) + { + return mode switch + { + DataRootMode.Package => "package", + DataRootMode.Standard => "standard", + _ => "custom" + }; + } + + public static DataRootMode Parse(string? value) + { + return value?.Trim().ToLowerInvariant() switch + { + "package" => DataRootMode.Package, + "standard" => DataRootMode.Standard, + _ => DataRootMode.Custom + }; + } + + public static string ToDisplayKey(this DataRootSource source) + { + return source switch + { + DataRootSource.CommandLine => "command-line", + DataRootSource.Environment => "environment", + DataRootSource.Anchor => "anchor", + DataRootSource.Legacy => "legacy", + DataRootSource.RepairedPayload => "repaired", + DataRootSource.ModeDefault => "default", + _ => "unknown" + }; + } +} + +/// +/// The persisted data-root anchor. It deliberately lives outside the data directory: it must stay readable +/// before the root is known, and it must never travel inside a backup, export, or cloud archive. +/// +public sealed class DataRootAnchor +{ + public const int CurrentSchemaVersion = 1; + + public int SchemaVersion { get; set; } = CurrentSchemaVersion; + + /// One of package, standard, or custom. + public string Mode { get; set; } = "standard"; + + public string DataRoot { get; set; } = string.Empty; + + /// The package marker kind that wrote this anchor, when the package carried one. + public string? PackageKind { get; set; } + + public DateTimeOffset UpdatedAtUtc { get; set; } = DateTimeOffset.UtcNow; +} + +public enum DataRootAnchorStatus +{ + Missing = 0, + Valid = 1, + Invalid = 2 +} + +public readonly record struct DataRootAnchorReadResult( + DataRootAnchorStatus Status, + DataRootAnchor? Anchor, + string? ErrorMessage); + +/// Everything the desktop resolver needs; all optional values exist so tests and tools can pin them. +public sealed record DesktopDataRootOptions +{ + /// Directory that holds the running payload; defaults to . + public string? AppDirectory { get; init; } + + /// Package root override (normally SECRANDOM_PACKAGE_ROOT). + public string? PackageRoot { get; init; } + + /// Value of --data-root, when present. + public string? CommandLineDataRoot { get; init; } + + /// Value of SECRANDOM_DATA_ROOT, when present. + public string? EnvironmentDataRoot { get; init; } + + /// Whether this build is a development build; development builds keep data beside the payload. + public bool IsDevelopmentBuild { get; init; } + + /// Test/tool override for the anchor file path. + public string? AnchorPath { get; init; } + + /// Test/tool override for the platform standard data root. + public string? StandardDataRoot { get; init; } + + /// Test/tool override for the platform standard anchor directory. + public string? StandardAnchorDirectory { get; init; } + + /// Disable persistence for tests that must not touch the user profile. + public bool WriteAnchor { get; init; } = true; + + /// Package marker kind, when already known; otherwise the resolver reads it from the payload. + public string? PackageKind { get; init; } +} + +/// The pure resolution result, before any directory is created or write-probed. +public sealed record DesktopDataRootResolution +{ + public required string AppDirectory { get; init; } + public required string PackageRoot { get; init; } + public required bool IsPortablePackage { get; init; } + public required DataRootMode Mode { get; init; } + public required DataRootSource Source { get; init; } + public required string DataRoot { get; init; } + public required string AnchorPath { get; init; } + public string? PackageKind { get; init; } + + /// A payload-local data directory that must be folded into before use. + public string? PayloadDataRootToRepair { get; init; } + + /// Other known data locations that still hold data; never merged automatically. + public IReadOnlyList OtherDataRoots { get; init; } = []; + + /// True when the resolved root is not the location this mode would create today. + public bool NeedsMigrationNotice { get; init; } +} \ No newline at end of file diff --git a/SecRandom.Shared/DataRoot/DesktopDataRootResolver.cs b/SecRandom.Shared/DataRoot/DesktopDataRootResolver.cs new file mode 100644 index 000000000..915941c53 --- /dev/null +++ b/SecRandom.Shared/DataRoot/DesktopDataRootResolver.cs @@ -0,0 +1,185 @@ +namespace SecRandom.Shared.DataRoot; + +/// +/// Resolution order for the desktop data root: +/// --data-root → SECRANDOM_DATA_ROOT → anchor → legacy claim → mode default. +/// A legacy location is only claimed while the new default is empty, so an upgrade never silently starts +/// from an empty directory while the user's data still sits somewhere else. +/// +public static class DesktopDataRootResolver +{ + public static DesktopDataRootResolution Resolve(DesktopDataRootOptions options) + { + ArgumentNullException.ThrowIfNull(options); + + var appDirectory = Path.GetFullPath(options.AppDirectory ?? AppContext.BaseDirectory); + var packageRoot = ResolvePackageRoot(appDirectory, options.PackageRoot); + var packageKind = options.PackageKind ?? DataRootPaths.ReadPackageKind(appDirectory); + var isPortable = DataRootPaths.IsPortablePackageLayout(packageRoot, appDirectory) + && DataRootPaths.IsPortablePackageKind(packageKind); + + var anchorPath = options.AnchorPath ?? DataRootPaths.GetAnchorPath(packageRoot, isPortable); + var standardDataRoot = Path.GetFullPath(options.StandardDataRoot ?? DataRootPaths.GetStandardDataRoot()); + var packageDataRoot = Path.Combine(packageRoot, DataRootPaths.DataDirectoryName); + var defaultMode = isPortable || options.IsDevelopmentBuild + ? DataRootMode.Package + : DataRootMode.Standard; + var defaultRoot = defaultMode == DataRootMode.Package ? packageDataRoot : standardDataRoot; + + var payloadDataRoots = DataRootPaths.EnumeratePayloadDirectories(packageRoot) + .Select(directory => Path.Combine(directory, DataRootPaths.DataDirectoryName)) + .Where(DataRootPaths.HasData) + .ToArray(); + + var others = new List(); + void RememberOther(string? candidate, string currentRoot) + { + if (string.IsNullOrWhiteSpace(candidate) + || !DataRootPaths.HasData(candidate) + || DataRootPaths.PathEquals(candidate, currentRoot) + || others.Any(existing => DataRootPaths.PathEquals(existing, candidate))) + return; + + others.Add(Path.GetFullPath(candidate)); + } + + if (!string.IsNullOrWhiteSpace(options.CommandLineDataRoot)) + { + var root = Path.GetFullPath(options.CommandLineDataRoot); + RememberOther(packageDataRoot, root); + RememberOther(standardDataRoot, root); + foreach (var payloadRoot in payloadDataRoots) + RememberOther(payloadRoot, root); + return Build(root, DataRootMode.Custom, DataRootSource.CommandLine, needsNotice: false); + } + + if (!string.IsNullOrWhiteSpace(options.EnvironmentDataRoot)) + { + var root = Path.GetFullPath(options.EnvironmentDataRoot); + RememberOther(packageDataRoot, root); + RememberOther(standardDataRoot, root); + foreach (var payloadRoot in payloadDataRoots) + RememberOther(payloadRoot, root); + return Build(root, DataRootMode.Custom, DataRootSource.Environment, needsNotice: false); + } + + var anchorResult = DataRootAnchorStore.Read(anchorPath); + if (anchorResult is { Status: DataRootAnchorStatus.Valid, Anchor: { } anchor }) + { + var root = Path.GetFullPath(anchor.DataRoot); + RememberOther(packageDataRoot, root); + RememberOther(standardDataRoot, root); + foreach (var payloadRoot in payloadDataRoots) + RememberOther(payloadRoot, root); + + return Build( + root, + DataRootModeExtensions.Parse(anchor.Mode), + DataRootSource.Anchor, + needsNotice: IsUnprotectedLayout(root)); + } + + // No anchor: claim the first location that actually holds data, newest expectations first. + if (isPortable || options.IsDevelopmentBuild) + { + if (DataRootPaths.HasData(packageDataRoot)) + { + RememberOther(standardDataRoot, packageDataRoot); + foreach (var payloadRoot in payloadDataRoots) + RememberOther(payloadRoot, packageDataRoot); + return Build(packageDataRoot, DataRootMode.Package, DataRootSource.ModeDefault, needsNotice: false); + } + + if (payloadDataRoots.Length > 0) + { + foreach (var payloadRoot in payloadDataRoots) + RememberOther(payloadRoot, packageDataRoot); + return Build( + packageDataRoot, + DataRootMode.Package, + DataRootSource.RepairedPayload, + needsNotice: false, + payloadDataRootToRepair: payloadDataRoots[0]); + } + + RememberOther(standardDataRoot, packageDataRoot); + return Build(packageDataRoot, DataRootMode.Package, DataRootSource.ModeDefault, needsNotice: false); + } + + if (DataRootPaths.HasData(standardDataRoot)) + { + RememberOther(packageDataRoot, standardDataRoot); + foreach (var payloadRoot in payloadDataRoots) + RememberOther(payloadRoot, standardDataRoot); + return Build(standardDataRoot, DataRootMode.Standard, DataRootSource.ModeDefault, needsNotice: false); + } + + if (DataRootPaths.HasData(packageDataRoot)) + { + RememberOther(standardDataRoot, packageDataRoot); + foreach (var payloadRoot in payloadDataRoots) + RememberOther(payloadRoot, packageDataRoot); + return Build( + packageDataRoot, + DataRootMode.Package, + DataRootSource.Legacy, + needsNotice: true); + } + + if (payloadDataRoots.Length > 0) + { + foreach (var payloadRoot in payloadDataRoots) + RememberOther(payloadRoot, packageDataRoot); + return Build( + packageDataRoot, + DataRootMode.Package, + DataRootSource.RepairedPayload, + needsNotice: true, + payloadDataRootToRepair: payloadDataRoots[0]); + } + + RememberOther(packageDataRoot, standardDataRoot); + return Build(standardDataRoot, DataRootMode.Standard, DataRootSource.ModeDefault, needsNotice: false); + + DesktopDataRootResolution Build( + string root, + DataRootMode mode, + DataRootSource source, + bool needsNotice, + string? payloadDataRootToRepair = null) + { + return new DesktopDataRootResolution + { + AppDirectory = appDirectory, + PackageRoot = packageRoot, + IsPortablePackage = isPortable, + Mode = mode, + Source = source, + DataRoot = Path.TrimEndingDirectorySeparator(Path.GetFullPath(root)), + AnchorPath = Path.GetFullPath(anchorPath), + PackageKind = packageKind, + PayloadDataRootToRepair = payloadDataRootToRepair, + OtherDataRoots = others.ToArray(), + NeedsMigrationNotice = needsNotice + }; + } + + bool IsUnprotectedLayout(string root) + { + // A root inside the running payload is replaced by the next update, no matter the mode. + return DataRootPaths.IsSameOrNested(appDirectory, root); + } + } + + /// Same package-root rule the rest of the app uses: portable layout wins over the executable folder. + public static string ResolvePackageRoot(string appDirectory, string? configuredPackageRoot) + { + if (DataRootPaths.IsPortablePackageLayout(configuredPackageRoot!, appDirectory)) + return Path.GetFullPath(configuredPackageRoot!); + + var parent = Directory.GetParent(Path.GetFullPath(appDirectory))?.FullName; + return DataRootPaths.IsPortablePackageLayout(parent!, appDirectory) + ? Path.GetFullPath(parent!) + : Path.GetFullPath(appDirectory); + } +} \ No newline at end of file diff --git a/SecRandom.Shared/Utils.cs b/SecRandom.Shared/Utils.cs index 2272a36f0..b61a8ed2f 100644 --- a/SecRandom.Shared/Utils.cs +++ b/SecRandom.Shared/Utils.cs @@ -1,23 +1,56 @@ using System.ComponentModel; -using System.Text.Json; +using SecRandom.Shared.DataRoot; namespace SecRandom.Shared; public static class Utils { public const string PackageRootEnvironmentVariable = "SECRANDOM_PACKAGE_ROOT"; + // Keep this a literal: the compiler rejects the cross-type const reference in this + // multi-targeted assembly (CS0133), while the wire value must stay identical to + // DataRootCommandLine.DataRootEnvironmentVariable. + public const string DataRootEnvironmentVariable = "SECRANDOM_DATA_ROOT"; private const string ConfigDirectoryName = "config"; private const string UnixHiddenEntriesFileName = ".hidden"; private static readonly object DataRootGate = new(); private static string? _configuredDataRoot; private static bool _dataRootWasRead; private static DesktopDataRootPreparationResult? _desktopPreparation; + private static DataRootMode _dataRootMode = DataRootMode.Package; + private static DataRootSource _dataRootSource = DataRootSource.Unknown; + private static string? _anchorPath; + private static IReadOnlyList _otherDataRoots = []; + private static bool _isPortablePackage; + private static bool _needsMigrationNotice; public readonly record struct DesktopDataRootPreparationResult( bool IsPortablePackage, bool IsWritable, string DataRoot, - string? ErrorMessage); + string? ErrorMessage, + DataRootMode Mode = DataRootMode.Package, + DataRootSource Source = DataRootSource.Unknown, + string? AnchorPath = null, + IReadOnlyList? OtherDataRoots = null, + bool NeedsMigrationNotice = false); + + /// The mode the current data root was chosen in. + public static DataRootMode DataRootMode => _dataRootMode; + + /// Why the current data root won; diagnostic and storage-page metadata, not a policy switch. + public static DataRootSource DataRootSource => _dataRootSource; + + /// Anchor file that persists the current mode and root; before preparation. + public static string? AnchorPath => _anchorPath; + + /// Other known data locations that still hold data and were deliberately not merged. + public static IReadOnlyList OtherDataRoots => _otherDataRoots; + + /// True when the running payload belongs to a portable ZIP package. + public static bool IsPortablePackage => _isPortablePackage; + + /// True when the current root differs from the location this mode would create on a fresh install. + public static bool NeedsMigrationNotice => _needsMigrationNotice; public static string PackageRoot => ResolvePackageRoot(); @@ -63,18 +96,28 @@ public static string GetMobileDataRootPath() } /// - /// Checks the desktop package data directory before the first persisted path is used. - /// Installed packages fall back to LocalApplicationData; portable packages must remain - /// beside the executable so they can be moved as one unit. + /// Resolves and fixates the desktop data root. The resolution order lives in + /// ; this method only turns the pure result into the process-wide root: + /// it repairs payload-local data, probes writability, and persists the anchor when the choice is worth keeping. /// - public static DesktopDataRootPreparationResult PrepareDesktopDataRoot() + public static DesktopDataRootPreparationResult PrepareDesktopDataRoot( + bool isDevelopmentBuild, + string? commandLineDataRoot = null) { - var packageRoot = ResolvePackageRoot(); - return PrepareDesktopDataRoot(packageRoot, IsPortablePackage(packageRoot)); + return PrepareDesktopDataRoot(new DesktopDataRootOptions + { + AppDirectory = Path.GetFullPath(AppContext.BaseDirectory), + PackageRoot = Environment.GetEnvironmentVariable(PackageRootEnvironmentVariable), + CommandLineDataRoot = commandLineDataRoot, + EnvironmentDataRoot = Environment.GetEnvironmentVariable(DataRootEnvironmentVariable), + IsDevelopmentBuild = isDevelopmentBuild + }); } - private static DesktopDataRootPreparationResult PrepareDesktopDataRoot(string packageRoot, bool isPortablePackage) + public static DesktopDataRootPreparationResult PrepareDesktopDataRoot(DesktopDataRootOptions options) { + ArgumentNullException.ThrowIfNull(options); + lock (DataRootGate) { if (_desktopPreparation is { } prepared) @@ -84,38 +127,52 @@ private static DesktopDataRootPreparationResult PrepareDesktopDataRoot(string pa if (_configuredDataRoot is not null) throw new InvalidOperationException("The data root has already been configured."); - var packageDataRoot = Path.Combine(packageRoot, "data"); - if (TryVerifyWritable(packageDataRoot, out var packageError)) + var resolution = DesktopDataRootResolver.Resolve(options); + var payloadDataRootToRepair = resolution.PayloadDataRootToRepair; + var repairError = payloadDataRootToRepair is { } payloadDataRoot + ? RepairPayloadDataRoot(payloadDataRoot, resolution.DataRoot) + : null; + if (repairError is not null) { - _configuredDataRoot = Path.GetFullPath(packageDataRoot); - _dataRootWasRead = true; - var result = new DesktopDataRootPreparationResult(isPortablePackage, true, _configuredDataRoot, null); - _desktopPreparation = result; - return result; + // The repair did not finish, so the payload copy stays authoritative for this run: letting an + // update replace it is bad, but pointing the app at a half-copied directory is worse. + resolution = resolution with + { + DataRoot = Path.GetFullPath(payloadDataRootToRepair!), + PayloadDataRootToRepair = null + }; } - if (isPortablePackage) - { - _configuredDataRoot = Path.GetFullPath(packageDataRoot); - _dataRootWasRead = true; - var result = new DesktopDataRootPreparationResult(true, false, _configuredDataRoot, packageError); - _desktopPreparation = result; - return result; - } - - var fallbackRoot = GetDesktopFallbackDataRoot(); - if (!TryVerifyWritable(fallbackRoot, out var fallbackError)) - { - throw new InvalidOperationException( - $"Neither the installed package data directory nor the per-user data directory is writable. " + - $"Package: {packageDataRoot}; fallback: {fallbackRoot}; {fallbackError}"); - } + var dataRoot = Path.GetFullPath(resolution.DataRoot); + var writable = DataRootPaths.TryVerifyWritable(dataRoot, out var writeError); + var otherDataRoots = resolution.OtherDataRoots + .Where(candidate => !DataRootPaths.PathEquals(candidate, dataRoot)) + .ToArray(); - _configuredDataRoot = Path.GetFullPath(fallbackRoot); + _configuredDataRoot = dataRoot; _dataRootWasRead = true; - var fallbackResult = new DesktopDataRootPreparationResult(false, true, _configuredDataRoot, packageError); - _desktopPreparation = fallbackResult; - return fallbackResult; + _dataRootMode = resolution.Mode; + _dataRootSource = resolution.Source; + _anchorPath = resolution.AnchorPath; + _otherDataRoots = otherDataRoots; + _isPortablePackage = resolution.IsPortablePackage; + _needsMigrationNotice = resolution.NeedsMigrationNotice; + + if (writable && ShouldPersistAnchor(resolution, options)) + DataRootAnchorStore.TryPersist(resolution with { DataRoot = dataRoot }, write: true); + + var result = new DesktopDataRootPreparationResult( + resolution.IsPortablePackage, + writable, + dataRoot, + writeError ?? repairError, + resolution.Mode, + resolution.Source, + resolution.AnchorPath, + otherDataRoots, + resolution.NeedsMigrationNotice); + _desktopPreparation = result; + return result; } } @@ -265,108 +322,92 @@ private static bool TryGetPortableLauncherPath( private static string ResolvePackageRoot() { - var appDirectory = Path.GetFullPath(AppContext.BaseDirectory); - var configuredRoot = Environment.GetEnvironmentVariable(PackageRootEnvironmentVariable); - if (IsPortablePackageRoot(configuredRoot, appDirectory)) - return Path.GetFullPath(configuredRoot!); - - var parent = Directory.GetParent(appDirectory)?.FullName; - return IsPortablePackageRoot(parent, appDirectory) ? Path.GetFullPath(parent!) : appDirectory; + return DesktopDataRootResolver.ResolvePackageRoot( + Path.GetFullPath(AppContext.BaseDirectory), + Environment.GetEnvironmentVariable(PackageRootEnvironmentVariable)); } - private static string GetDesktopFallbackDataRoot() + /// An integration entry that outlives this build must only point at the launcher that accepts it. + private static bool IsPortablePackageRoot(string? candidate, string appDirectory) { - var localApplicationData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); - if (string.IsNullOrWhiteSpace(localApplicationData)) - throw new InvalidOperationException("The platform does not provide a per-user data directory."); - - return Path.Combine(localApplicationData, "SecRandom", "data"); + return DataRootPaths.IsPortablePackageLayout(candidate!, appDirectory); } - private static bool IsPortablePackage(string packageRoot) + private static bool HasPortablePayloadKind(string appDirectory) { - var appDirectory = Path.GetFullPath(AppContext.BaseDirectory); - return IsPortablePackageRoot(packageRoot, appDirectory) - && HasPortablePayloadKind(appDirectory); + return DataRootPaths.IsPortablePackageKind(DataRootPaths.ReadPackageKind(appDirectory)); } - private static bool HasPortablePayloadKind(string appDirectory) + private static bool ShouldPersistAnchor(DesktopDataRootResolution resolution, DesktopDataRootOptions options) { - var markerPath = Path.Combine(appDirectory, "SecRandom.package.json"); - try - { - using var marker = JsonDocument.Parse(File.ReadAllText(markerPath)); - return marker.RootElement.TryGetProperty("packageKind", out var packageKind) - && string.Equals(packageKind.GetString(), "portable-zip", StringComparison.Ordinal); - } - catch (IOException) - { - return false; - } - catch (UnauthorizedAccessException) - { + // Explicit overrides are one-shot by design: a --data-root run must not silently become the permanent root. + if (resolution.Source is DataRootSource.CommandLine or DataRootSource.Environment) return false; - } - catch (JsonException) - { + + // Development builds keep data beside the payload and otherwise litter bin/Debug with an anchor. + if (options.IsDevelopmentBuild && resolution.Mode == DataRootMode.Package) return false; - } + + return !string.IsNullOrWhiteSpace(resolution.AnchorPath); } - private static bool TryVerifyWritable(string directory, out string? errorMessage) + /// + /// Moves data an older layout left inside a versioned payload directory out to the stable root. + /// Copy-then-delete keeps the payload copy intact when the copy fails halfway. + /// + private static string? RepairPayloadDataRoot(string payloadDataRoot, string dataRoot) { - var testFile = Path.Combine(directory, $".secrandom-write-test-{Guid.NewGuid():N}.tmp"); + var source = Path.GetFullPath(payloadDataRoot); + var target = Path.GetFullPath(dataRoot); + if (DataRootPaths.PathEquals(source, target)) + return null; + + var copied = new List(); try { - Directory.CreateDirectory(directory); - using (var stream = new FileStream(testFile, FileMode.CreateNew, FileAccess.Write, FileShare.None)) + Directory.CreateDirectory(target); + foreach (var file in Directory.EnumerateFiles(source, "*", SearchOption.AllDirectories)) { - stream.WriteByte(0); - stream.Flush(true); + var destination = Path.Combine(target, Path.GetRelativePath(source, file)); + var directory = Path.GetDirectoryName(destination); + if (!string.IsNullOrEmpty(directory)) + Directory.CreateDirectory(directory); + if (File.Exists(destination)) + continue; + + File.Copy(file, destination); + copied.Add(file); } - - File.Delete(testFile); - errorMessage = null; - return true; } catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or - NotSupportedException or ArgumentException) + NotSupportedException) + { + return exception.Message; + } + + foreach (var file in copied) { try { - if (File.Exists(testFile)) - File.Delete(testFile); + File.Delete(file); } - catch (IOException) + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) { - // The original write error is more useful to the caller. + // The payload copy is replaced by the next update anyway; leaving it only costs disk space. } - catch (UnauthorizedAccessException) - { - // The original write error is more useful to the caller. - } - - errorMessage = exception.Message; - return false; } - } - private static bool IsPortablePackageRoot(string? candidate, string appDirectory) - { - if (string.IsNullOrWhiteSpace(candidate) || !Directory.Exists(candidate)) - return false; - - var root = Path.GetFullPath(candidate); - var normalizedAppDirectory = Path.GetFullPath(appDirectory); - var parent = Directory.GetParent(normalizedAppDirectory)?.FullName; - if (!string.Equals(root, parent, OperatingSystem.IsWindows() - ? StringComparison.OrdinalIgnoreCase - : StringComparison.Ordinal)) - return false; + try + { + if (!Directory.EnumerateFileSystemEntries(source).Any()) + Directory.Delete(source); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + // Cleanup is cosmetic; the target root already holds every file. + } - var appDirectoryName = Path.GetFileName(normalizedAppDirectory.TrimEnd(Path.DirectorySeparatorChar)); - return appDirectoryName.StartsWith("app-", StringComparison.Ordinal) - && File.Exists(Path.Combine(normalizedAppDirectory, "SecRandom.package.json")); + return null; } internal static void ResetDataRootForTests() @@ -376,6 +417,12 @@ internal static void ResetDataRootForTests() _configuredDataRoot = null; _dataRootWasRead = false; _desktopPreparation = null; + _dataRootMode = DataRootMode.Package; + _dataRootSource = DataRootSource.Unknown; + _anchorPath = null; + _otherDataRoots = []; + _isPortablePackage = false; + _needsMigrationNotice = false; } } diff --git a/SecRandom/Controls/AttachedSettings/DrawImageAttachedSettingsControl.axaml.cs b/SecRandom/Controls/AttachedSettings/DrawImageAttachedSettingsControl.axaml.cs index d76f9002f..aac84e07b 100644 --- a/SecRandom/Controls/AttachedSettings/DrawImageAttachedSettingsControl.axaml.cs +++ b/SecRandom/Controls/AttachedSettings/DrawImageAttachedSettingsControl.axaml.cs @@ -11,6 +11,7 @@ using SecRandom.Core.Icons; using SecRandom.Core.Models.AttachedSettings; using SecRandom.Shared; +using SecRandom.Shared.DataRoot; namespace SecRandom.Controls.AttachedSettings; @@ -68,7 +69,9 @@ private async void BrowseImage_OnClick(object? sender, Avalonia.Interactivity.Ro var path = files.FirstOrDefault()?.TryGetLocalPath(); if (!string.IsNullOrWhiteSpace(path)) { - ImagePath = path; + // Data-root-relative whenever the picture lives inside it: moving the data root must not orphan the + // reference, and an external picture keeps its absolute path untouched. + ImagePath = DataPathReference.ToStored(path, Utils.DataRoot); return; } @@ -84,7 +87,7 @@ private async void BrowseImage_OnClick(object? sender, Avalonia.Interactivity.Ro await using var source = await file.OpenReadAsync(); await using var target = File.Create(managedPath); await source.CopyToAsync(target); - ImagePath = managedPath; + ImagePath = DataPathReference.ToStored(managedPath, Utils.DataRoot); } private void OnPropertyChanged(string? propertyName = null) diff --git a/SecRandom/Langs/Common/Resources.Designer.cs b/SecRandom/Langs/Common/Resources.Designer.cs index 9d0ab8e8d..d0d5a8efe 100644 --- a/SecRandom/Langs/Common/Resources.Designer.cs +++ b/SecRandom/Langs/Common/Resources.Designer.cs @@ -213,6 +213,29 @@ public static string Feat_Timer { } } + /// + /// Looks up a localized string similar to SecRandom 无法创建或写入当前数据目录,因此无法继续启动 + /// + ///数据目录: {0} + ///错误: {1} + /// + ///请检查该目录的权限,或使用 --data-root 指定其他位置. + /// + public static string M_DataRootUnavailableContent { + get { + return ResourceManager.GetString("M_DataRootUnavailableContent", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 无法使用数据目录. + /// + public static string M_DataRootUnavailableTitle { + get { + return ResourceManager.GetString("M_DataRootUnavailableTitle", resourceCulture); + } + } + /// /// Looks up a localized string similar to SecRandom 便携版必须能够写入其所在目录中的 data 文件夹 /// diff --git a/SecRandom/Langs/Common/Resources.en-US.resx b/SecRandom/Langs/Common/Resources.en-US.resx index 2ee8a395b..203078183 100644 --- a/SecRandom/Langs/Common/Resources.en-US.resx +++ b/SecRandom/Langs/Common/Resources.en-US.resx @@ -55,12 +55,22 @@ Closes automatically in {0} seconds Click 3 times in a row to close + + Cancel + Click 3 times in a row to close Close + Data directory unavailable + SecRandom cannot create or write to its data directory, so it cannot start. + +Data directory: {0} +Error: {1} + +Check that directory's permissions, or pass --data-root to use another location. Portable Data Directory Is Not Writable diff --git a/SecRandom/Langs/Common/Resources.ja-JP.resx b/SecRandom/Langs/Common/Resources.ja-JP.resx index 33c7906e6..8d3a062f1 100644 --- a/SecRandom/Langs/Common/Resources.ja-JP.resx +++ b/SecRandom/Langs/Common/Resources.ja-JP.resx @@ -35,8 +35,18 @@ クイック抽選 タイマー {0} 秒後に自動的に閉じます 3 回連続クリックで閉じます + + キャンセル + 3 回連続クリックで閉じます 閉じる + データフォルダーを使用できません + SecRandom はデータフォルダーを作成または書き込みできないため、起動を続行できません。 + +データフォルダー: {0} +エラー: {1} + +このフォルダーのアクセス権を確認するか、--data-root で別の場所を指定してください。 ポータブル版のデータフォルダーに書き込めません SecRandom ポータブル版は、同梱の data フォルダーに書き込める必要があります diff --git a/SecRandom/Langs/Common/Resources.resx b/SecRandom/Langs/Common/Resources.resx index c703e6f44..c3586f340 100644 --- a/SecRandom/Langs/Common/Resources.resx +++ b/SecRandom/Langs/Common/Resources.resx @@ -133,6 +133,17 @@ 关闭 + + 无法使用数据目录 + + + SecRandom 无法创建或写入当前数据目录,因此无法继续启动 + +数据目录: {0} +错误: {1} + +请检查该目录的权限,或使用 --data-root 指定其他位置 + 无法写入便携版数据目录 diff --git a/SecRandom/Langs/DataRootMigration/Resources.Designer.cs b/SecRandom/Langs/DataRootMigration/Resources.Designer.cs new file mode 100644 index 000000000..0a93882ca --- /dev/null +++ b/SecRandom/Langs/DataRootMigration/Resources.Designer.cs @@ -0,0 +1,177 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace SecRandom.Langs.DataRootMigration { + using System; + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + public class Resources { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() { + } + + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + public static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("SecRandom.Langs.DataRootMigration.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + public static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + + /// + /// Looks up a localized string similar to 数据已迁移到:{0}. + /// + public static string W_CompletedDetail { + get { + return ResourceManager.GetString("W_CompletedDetail", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 迁移完成. + /// + public static string W_Completed { + get { + return ResourceManager.GetString("W_Completed", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 正在切换到新位置…. + /// + public static string W_Committing { + get { + return ResourceManager.GetString("W_Committing", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 正在复制数据({0} / {1} 个文件). + /// + public static string W_Copying { + get { + return ResourceManager.GetString("W_Copying", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 退出. + /// + public static string W_Exit { + get { + return ResourceManager.GetString("W_Exit", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 迁移失败. + /// + public static string W_Failed { + get { + return ResourceManager.GetString("W_Failed", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 未做任何更改,或原数据目录仍然完整。 + /// + public static string W_FailedDetail { + get { + return ResourceManager.GetString("W_FailedDetail", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 找不到这次迁移的记录,未做任何更改。. + /// + public static string W_JournalMissing { + get { + return ResourceManager.GetString("W_JournalMissing", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 原数据目录已保留:{0}. + /// + public static string W_OldDirectoryKept { + get { + return ResourceManager.GetString("W_OldDirectoryKept", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 正在准备迁移…. + /// + public static string W_Preparing { + get { + return ResourceManager.GetString("W_Preparing", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 重启应用. + /// + public static string W_Restart { + get { + return ResourceManager.GetString("W_Restart", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 重试. + /// + public static string W_Retry { + get { + return ResourceManager.GetString("W_Retry", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 数据目录迁移. + /// + public static string W_Title { + get { + return ResourceManager.GetString("W_Title", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 正在校验复制结果…. + /// + public static string W_Verifying { + get { + return ResourceManager.GetString("W_Verifying", resourceCulture); + } + } + } +} \ No newline at end of file diff --git a/SecRandom/Langs/DataRootMigration/Resources.en-US.resx b/SecRandom/Langs/DataRootMigration/Resources.en-US.resx new file mode 100644 index 000000000..445be9dee --- /dev/null +++ b/SecRandom/Langs/DataRootMigration/Resources.en-US.resx @@ -0,0 +1,31 @@ + + + + text/microsoft-resx + + + 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 + + Data directory migration + Preparing the migration… + Copying data ({0} of {1} files) + Verifying the copied data… + Switching to the new location… + Migration completed + Your data is now at: {0} + The old data directory was kept at: {0} + Migration failed + Nothing was changed, or the old data directory is still intact. + +{0} + The record for this migration could not be found. Nothing was changed. + Retry + Restart app + Exit + \ No newline at end of file diff --git a/SecRandom/Langs/DataRootMigration/Resources.ja-JP.resx b/SecRandom/Langs/DataRootMigration/Resources.ja-JP.resx new file mode 100644 index 000000000..5596be772 --- /dev/null +++ b/SecRandom/Langs/DataRootMigration/Resources.ja-JP.resx @@ -0,0 +1,31 @@ + + + + text/microsoft-resx + + + 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 + + データフォルダーの移行 + 移行を準備しています… + データをコピーしています({0} / {1} ファイル) + コピーしたデータを検証しています… + 新しい場所に切り替えています… + 移行が完了しました + データは次の場所に移行されました:{0} + 元のデータフォルダーは次の場所に保持されています:{0} + 移行に失敗しました + 変更は行われていないか、元のフォルダーはそのまま残っています。 + +{0} + この移行の記録が見つかりません。変更は行われていません。 + 再試行 + アプリを再起動 + 終了 + \ No newline at end of file diff --git a/SecRandom/Langs/DataRootMigration/Resources.resx b/SecRandom/Langs/DataRootMigration/Resources.resx new file mode 100644 index 000000000..9ae032854 --- /dev/null +++ b/SecRandom/Langs/DataRootMigration/Resources.resx @@ -0,0 +1,59 @@ + + + + text/microsoft-resx + + + 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 + + + 数据目录迁移 + + + 正在准备迁移… + + + 正在复制数据({0} / {1} 个文件) + + + 正在校验复制结果… + + + 正在切换到新位置… + + + 迁移完成 + + + 数据已迁移到:{0} + + + 原数据目录已保留:{0} + + + 迁移失败 + + + 未做任何更改,或原数据目录仍然完整。 + +{0} + + + 找不到这次迁移的记录,未做任何更改。 + + + 重试 + + + 重启应用 + + + 退出 + + \ No newline at end of file diff --git a/SecRandom/Langs/SettingsPages/General/Storage/Resources.Designer.cs b/SecRandom/Langs/SettingsPages/General/Storage/Resources.Designer.cs new file mode 100644 index 000000000..76fcedd6d --- /dev/null +++ b/SecRandom/Langs/SettingsPages/General/Storage/Resources.Designer.cs @@ -0,0 +1,337 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace SecRandom.Langs.SettingsPages.General.Storage { + using System; + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + public class Resources { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + public static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("SecRandom.Langs.SettingsPages.General.Storage.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + public static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + + /// + /// Looks up a localized string similar to 数据存储. + /// + public static string Page_Title { + get { + return ResourceManager.GetString("Page_Title", resourceCulture); + } + } + + public static string S_Location { + get { + return ResourceManager.GetString("S_Location", resourceCulture); + } + } + + public static string S_Location_D { + get { + return ResourceManager.GetString("S_Location_D", resourceCulture); + } + } + + public static string S_CurrentRoot { + get { + return ResourceManager.GetString("S_CurrentRoot", resourceCulture); + } + } + + public static string S_CurrentRoot_D { + get { + return ResourceManager.GetString("S_CurrentRoot_D", resourceCulture); + } + } + + public static string S_Source { + get { + return ResourceManager.GetString("S_Source", resourceCulture); + } + } + + public static string S_Source_D { + get { + return ResourceManager.GetString("S_Source_D", resourceCulture); + } + } + + public static string S_AnchorPath { + get { + return ResourceManager.GetString("S_AnchorPath", resourceCulture); + } + } + + public static string S_AnchorPath_D { + get { + return ResourceManager.GetString("S_AnchorPath_D", resourceCulture); + } + } + + public static string S_Change { + get { + return ResourceManager.GetString("S_Change", resourceCulture); + } + } + + public static string S_Change_D { + get { + return ResourceManager.GetString("S_Change_D", resourceCulture); + } + } + + public static string S_Mode { + get { + return ResourceManager.GetString("S_Mode", resourceCulture); + } + } + + public static string S_Mode_D { + get { + return ResourceManager.GetString("S_Mode_D", resourceCulture); + } + } + + public static string O_Mode_Package { + get { + return ResourceManager.GetString("O_Mode_Package", resourceCulture); + } + } + + public static string O_Mode_Standard { + get { + return ResourceManager.GetString("O_Mode_Standard", resourceCulture); + } + } + + public static string O_Mode_Custom { + get { + return ResourceManager.GetString("O_Mode_Custom", resourceCulture); + } + } + + public static string S_Target { + get { + return ResourceManager.GetString("S_Target", resourceCulture); + } + } + + public static string S_Target_D { + get { + return ResourceManager.GetString("S_Target_D", resourceCulture); + } + } + + public static string C_Browse { + get { + return ResourceManager.GetString("C_Browse", resourceCulture); + } + } + + public static string C_Migrate { + get { + return ResourceManager.GetString("C_Migrate", resourceCulture); + } + } + + public static string S_OtherRoots { + get { + return ResourceManager.GetString("S_OtherRoots", resourceCulture); + } + } + + public static string S_OtherRoots_D { + get { + return ResourceManager.GetString("S_OtherRoots_D", resourceCulture); + } + } + + public static string M_LegacyNotice { + get { + return ResourceManager.GetString("M_LegacyNotice", resourceCulture); + } + } + + public static string M_NoOtherRoots { + get { + return ResourceManager.GetString("M_NoOtherRoots", resourceCulture); + } + } + + public static string M_DesktopOnly { + get { + return ResourceManager.GetString("M_DesktopOnly", resourceCulture); + } + } + + public static string M_RestartTitle { + get { + return ResourceManager.GetString("M_RestartTitle", resourceCulture); + } + } + + public static string M_RestartContent { + get { + return ResourceManager.GetString("M_RestartContent", resourceCulture); + } + } + + public static string M_Start { + get { + return ResourceManager.GetString("M_Start", resourceCulture); + } + } + + public static string C_Cancel { + get { + return ResourceManager.GetString("C_Cancel", resourceCulture); + } + } + + public static string M_Err_SourceMissing { + get { + return ResourceManager.GetString("M_Err_SourceMissing", resourceCulture); + } + } + + public static string M_Err_TargetInvalid { + get { + return ResourceManager.GetString("M_Err_TargetInvalid", resourceCulture); + } + } + + public static string M_Err_SameRoot { + get { + return ResourceManager.GetString("M_Err_SameRoot", resourceCulture); + } + } + + public static string M_Err_Nested { + get { + return ResourceManager.GetString("M_Err_Nested", resourceCulture); + } + } + + public static string M_Err_InsideApp { + get { + return ResourceManager.GetString("M_Err_InsideApp", resourceCulture); + } + } + + public static string M_Err_NotEmpty { + get { + return ResourceManager.GetString("M_Err_NotEmpty", resourceCulture); + } + } + + public static string M_Err_NotWritable { + get { + return ResourceManager.GetString("M_Err_NotWritable", resourceCulture); + } + } + + public static string M_Err_Journal { + get { + return ResourceManager.GetString("M_Err_Journal", resourceCulture); + } + } + + public static string M_Err_Unknown { + get { + return ResourceManager.GetString("M_Err_Unknown", resourceCulture); + } + } + + public static string M_RootUnavailable { + get { + return ResourceManager.GetString("M_RootUnavailable", resourceCulture); + } + } + + public static string Src_CommandLine { + get { + return ResourceManager.GetString("Src_CommandLine", resourceCulture); + } + } + + public static string Src_Environment { + get { + return ResourceManager.GetString("Src_Environment", resourceCulture); + } + } + + public static string Src_Anchor { + get { + return ResourceManager.GetString("Src_Anchor", resourceCulture); + } + } + + public static string Src_Legacy { + get { + return ResourceManager.GetString("Src_Legacy", resourceCulture); + } + } + + public static string Src_Repaired { + get { + return ResourceManager.GetString("Src_Repaired", resourceCulture); + } + } + + public static string Src_Default { + get { + return ResourceManager.GetString("Src_Default", resourceCulture); + } + } + + public static string Src_Unknown { + get { + return ResourceManager.GetString("Src_Unknown", resourceCulture); + } + } + } +} \ No newline at end of file diff --git a/SecRandom/Langs/SettingsPages/General/Storage/Resources.en-US.resx b/SecRandom/Langs/SettingsPages/General/Storage/Resources.en-US.resx new file mode 100644 index 000000000..e79dbe8c0 --- /dev/null +++ b/SecRandom/Langs/SettingsPages/General/Storage/Resources.en-US.resx @@ -0,0 +1,165 @@ + + + + + + + + + + text/microsoft-resx + + + 1.3 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, + PublicKeyToken=b77a5c561934e089 + + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, + PublicKeyToken=b77a5c561934e089 + + + + Data storage + + + Data directory + + + Settings, rosters, history, proofs, and images all live in this directory. + + + Current directory + + + The data directory in use; a change takes effect after a migration or restart. + + + Chosen by + + + Whether this directory came from a launch option, an environment variable, the stored anchor, or an older default location. + + + Anchor file + + + Records the selected data directory. It lives outside the data directory, so updating the app never overwrites it. + + + Change storage location + + + Switching locations copies the existing data to the new directory, verifies it, writes the anchor, and restarts the app. The old directory is renamed and kept until you delete it yourself. + + + Location type + + + The portable package directory follows the package; the standard location keeps data out of the program directory; a custom directory is whatever you choose. + + + Portable package directory (default) + + + System standard location (recommended) + + + Custom directory + + + Target directory + + + The target must be empty or not exist yet, and must not be inside the application directory. + + + Browse… + + + Migrate and restart + + + Other data directories found + + + These directories also hold data but are not in use. They are never migrated or deleted automatically; review and clean them up yourself. + + + The data still lives in the program directory. An app update replaces that directory, so migrating to the system standard location is recommended. + + + No other data directories were found. + + + On mobile the data directory is fixed by the system and cannot be changed. + + + Migrate and restart + + + The current data will be copied to: {0} It is then verified, the location is switched, and the app restarts automatically. The old directory is renamed and kept. + + + Start migration + + + Cancel + + + The current data directory does not exist, so it cannot be migrated. + + + The target directory is invalid; choose another location. + + + The target directory is the current data directory. + + + The target directory must not contain the current data directory or be inside it. + + + The target directory must not be inside the application directory, or an update would lose the data. + + + The target directory must be empty or not exist yet. + + + The target directory is not writable; check permissions or choose another location. + + + The migration journal could not be written; check permissions on the application data directory. + + + The migration cannot start: {0} + + + The current data directory is unavailable; fix the startup problem first. + + + Launch option + + + Environment variable + + + Anchor file + + + Legacy default location + + + Legacy layout repair + + + Default location + + + Unknown + + \ No newline at end of file diff --git a/SecRandom/Langs/SettingsPages/General/Storage/Resources.ja-JP.resx b/SecRandom/Langs/SettingsPages/General/Storage/Resources.ja-JP.resx new file mode 100644 index 000000000..dd3b5c0ae --- /dev/null +++ b/SecRandom/Langs/SettingsPages/General/Storage/Resources.ja-JP.resx @@ -0,0 +1,165 @@ + + + + + + + + + + text/microsoft-resx + + + 1.3 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, + PublicKeyToken=b77a5c561934e089 + + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, + PublicKeyToken=b77a5c561934e089 + + + + データ保存 + + + データフォルダー + + + 設定、名簿、履歴、証明、画像はすべてこのフォルダーに保存されます。 + + + 現在のフォルダー + + + 現在使用中のデータフォルダーです。変更は移行または再起動後に反映されます。 + + + 選択の由来 + + + このフォルダーが起動オプション、環境変数、保存された記録、旧既定位置のどれで選ばれたかを示します。 + + + 位置記録ファイル + + + 選択したデータフォルダーを記録するアンカーファイルです。データフォルダーの外にあるため、アプリの更新で上書きされません。 + + + 保存場所を変更 + + + 場所を切り替えると、既存データを新しいフォルダーへ複製し、検証後に位置記録を書き込んで自動的に再起動します。元のフォルダーは名前を変えて残るので、確認後に手動で削除できます。 + + + 場所の種類 + + + ポータブルパッケージ内はパッケージに追従します。システム標準の場所はプログラムフォルダーと分離されます。カスタムは任意の場所を指定します。 + + + ポータブルパッケージ内(既定) + + + システム標準の場所(推奨) + + + カスタムフォルダー + + + 移行先フォルダー + + + 移行先は空であるか、まだ存在しない必要があります。アプリのインストール先フォルダー内は指定できません。 + + + 選択… + + + 移行して再起動 + + + 見つかった他のデータフォルダー + + + これらのフォルダーにもデータがありますが、現在は使用されていません。誤った統合を避けるため、自動的な移行や削除は行いません。確認後に手動で整理してください。 + + + データがまだプログラムフォルダーに保存されています。アプリの更新でこのフォルダーが置き換わるため、システム標準の場所への移行を推奨します。 + + + 他のデータフォルダーは見つかりませんでした。 + + + モバイルではデータフォルダーはシステムに固定され、変更できません。 + + + 移行して再起動 + + + 現在のデータを次の場所へ複製します: {0} 複製後に検証して切り替え、自動的に再起動します。元のフォルダーは名前を変えて残ります。 + + + 移行を開始 + + + キャンセル + + + 現在のデータフォルダーが存在しないため移行できません。 + + + 移行先フォルダーが無効です。別の場所を選択してください。 + + + 移行先が現在のデータフォルダーと同じです。 + + + 移行先は現在のデータフォルダーを含む、またはその中にある場所にできません。 + + + 移行先はアプリのインストール先フォルダー内にできません。更新時にデータが失われます。 + + + 移行先は空であるか、まだ存在しない必要があります。 + + + 移行先に書き込めません。権限を確認するか別の場所を選択してください。 + + + 移行記録を書き込めません。アプリのデータフォルダーの権限を確認してください。 + + + 移行を開始できません: {0} + + + 現在のデータフォルダーを利用できません。先に起動の問題を解決してください。 + + + 起動オプション + + + 環境変数 + + + 位置記録 + + + 旧既定位置 + + + 旧レイアウト修復 + + + 既定位置 + + + 未記録 + + \ No newline at end of file diff --git a/SecRandom/Langs/SettingsPages/General/Storage/Resources.resx b/SecRandom/Langs/SettingsPages/General/Storage/Resources.resx new file mode 100644 index 000000000..58deafe4a --- /dev/null +++ b/SecRandom/Langs/SettingsPages/General/Storage/Resources.resx @@ -0,0 +1,165 @@ + + + + + + + + + + text/microsoft-resx + + + 1.3 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, + PublicKeyToken=b77a5c561934e089 + + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, + PublicKeyToken=b77a5c561934e089 + + + + 数据存储 + + + 数据目录 + + + 设置、名单、历史、证明和图片都保存在这个目录里。 + + + 当前目录 + + + 正在使用的数据目录,迁移或重启后生效。 + + + 位置来源 + + + 这个目录是按启动参数、环境变量、位置记录还是旧版默认位置选出的。 + + + 位置记录文件 + + + 记录所选数据目录的锚点文件。它保存在数据目录之外,更新应用不会覆盖它。 + + + 更改存储位置 + + + 切换位置会把现有数据完整复制到新目录,校验后写入位置记录并自动重启;原目录会改名保留,确认无误后可手动删除。 + + + 位置类型 + + + 便携包目录跟随便携包;系统标准位置与程序目录分离;自定义目录由你指定。 + + + 便携包目录(默认) + + + 系统标准位置(推荐) + + + 自定义目录 + + + 目标目录 + + + 目标必须为空或尚不存在,且不能位于应用安装目录内。 + + + 选择… + + + 迁移并重启 + + + 发现的其它数据目录 + + + 这些目录里也有数据,但当前没有被使用。为避免误合并,不会自动迁移或删除,请确认后自行清理。 + + + 检测到数据仍保存在程序目录中。应用更新会替换这个目录,建议迁移到系统标准位置。 + + + 未发现其它数据目录。 + + + 移动端的数据目录由系统固定,不能更改。 + + + 迁移并重启 + + + 应用会把当前数据复制到: {0} 复制完成后会校验、切换并自动重启。原目录会改名保留,不会自动删除。 + + + 开始迁移 + + + 取消 + + + 当前数据目录不存在,无法迁移。 + + + 目标目录无效,请重新选择。 + + + 目标目录与当前数据目录相同。 + + + 目标目录不能与当前数据目录互相包含。 + + + 目标目录不能位于应用安装目录内,否则更新时会丢失数据。 + + + 目标目录必须为空或尚不存在。 + + + 目标目录不可写,请检查权限或选择其它位置。 + + + 无法写入迁移记录,请检查应用数据目录的权限。 + + + 迁移无法开始:{0} + + + 当前数据目录不可用,请先修复启动问题。 + + + 启动参数 + + + 环境变量 + + + 位置记录 + + + 旧版默认位置 + + + 旧布局修复 + + + 默认位置 + + + 未记录 + + \ No newline at end of file diff --git a/SecRandom/Langs/SettingsPages/Update/Resources.en-US.resx b/SecRandom/Langs/SettingsPages/Update/Resources.en-US.resx index 0632a43d3..b797e53bf 100644 --- a/SecRandom/Langs/SettingsPages/Update/Resources.en-US.resx +++ b/SecRandom/Langs/SettingsPages/Update/Resources.en-US.resx @@ -1 +1 @@ -Update SettingsUpdate StrategyAutomatic update modeControl how often the program checks for and prompts about updatesOffNotifyDownloadInstallUpdate channelChoose stable or preview updatesStablePreviewBetaDevelopmentUpdate sourceAutomatic picks the lowest-latency source; a manual choice falls back in order when it failsAutomatic (recommended)Official mirrorGitHub思拓创联GitHub mirrorCheck for updatesInstall updateDownload and installForce check for updatesCheck for the latest version in the current channel, even if it is lower than the current versionCheck for updatesOnly checks signed complete release manifests; updates are not downloaded in the backgroundUpdate service not connectedThis page keeps the v2 settings entry points and options for future integration with a real update serviceLast check timeShow when updates were checked most recentlyUpdates have not been checkedChecking for updatesYou are up to dateNew version {0} foundNew version {0} found. Select a complete installerUpdate operation cancelledDownloading complete installer {0}Verifying installer integrityPreparing the application updateUpdate downloaded and ready to installRestarting to apply the updateSECTL distribution provides stable updates onlyNo update source is availableNo complete installer is available for the current system, architecture, and installation typeSECTL did not return a version tagUpdate metadata is emptyUpdate metadata is invalidUpdate channel {0} has no version tagUpdate manifest signature verification failed. Check the release key and sourceUpdate manifest is invalidUpdate manifest does not match the selected channelThe built-in update public key is invalidThe portable version is missing its stable Launcher and cannot deploy the version directory automatically. Download a new complete ZIP onceThe complete ZIP is missing its version directoryThe complete ZIP is missing its package markerThe complete ZIP does not match the current environmentThe target version directory already exists. Check for updates againThe complete ZIP is missing its LauncherInstaller size does not match the update manifestInstaller SHA-512 verification failedThe complete ZIP exceeds the safe file-count limitThe complete ZIP contains an invalid file pathThe extracted complete ZIP exceeds the safe size limitThe complete ZIP contains a path outside the packageThis installer type is not supportedUnable to start the system installerThe update manifest contains an unknown installer type +Update SettingsUpdate StrategyAutomatic update modeControl how often the program checks for and prompts about updatesOffNotifyDownloadInstallUpdate channelChoose stable or preview updatesStablePreviewBetaDevelopmentUpdate sourceAutomatic picks the lowest-latency source; a manual choice falls back in order when it failsAutomatic (recommended)Official mirrorGitHub思拓创联GitHub mirrorCheck for updatesInstall updateDownload and installForce check for updatesCheck for the latest version in the current channel, even if it is lower than the current versionCheck for updatesOnly checks signed complete release manifests; updates are not downloaded in the backgroundUpdate service not connectedThis page keeps the v2 settings entry points and options for future integration with a real update serviceLast check timeShow when updates were checked most recentlyUpdates have not been checkedChecking for updatesYou are up to dateNew version {0} foundNew version {0} found. Select a complete installerUpdate operation cancelledDownloading complete installer {0}Verifying installer integrityPreparing the application updateUpdate downloaded and ready to installRestarting to apply the updateSECTL distribution provides stable updates onlyNo update source is availableNo complete installer is available for the current system, architecture, and installation typeSECTL did not return a version tagUpdate metadata is emptyUpdate metadata is invalidUpdate channel {0} has no version tagUpdate manifest signature verification failed. Check the release key and sourceUpdate manifest is invalidUpdate manifest does not match the selected channelThe built-in update public key is invalidThe data directory is inside the version directory this update replaces, so updating would orphan it. Move the data directory first (Settings → General → Storage location), then retry the update.The portable version is missing its stable Launcher and cannot deploy the version directory automatically. Download a new complete ZIP onceThe complete ZIP is missing its version directoryThe complete ZIP is missing its package markerThe complete ZIP does not match the current environmentThe target version directory already exists. Check for updates againThe complete ZIP is missing its LauncherInstaller size does not match the update manifestInstaller SHA-512 verification failedThe complete ZIP exceeds the safe file-count limitThe complete ZIP contains an invalid file pathThe extracted complete ZIP exceeds the safe size limitThe complete ZIP contains a path outside the packageThis installer type is not supportedUnable to start the system installerThe update manifest contains an unknown installer type diff --git a/SecRandom/Langs/SettingsPages/Update/Resources.ja-JP.resx b/SecRandom/Langs/SettingsPages/Update/Resources.ja-JP.resx index faa1eef6b..c3432f00b 100644 --- a/SecRandom/Langs/SettingsPages/Update/Resources.ja-JP.resx +++ b/SecRandom/Langs/SettingsPages/Update/Resources.ja-JP.resx @@ -1 +1 @@ -更新設定更新方針自動更新モード更新の確認と通知の頻度を設定しますオフ自動確認して通知自動確認してダウンロード自動確認してインストール更新チャンネル安定版またはプレビュー版を選択します安定版プレビューベータ版開発版更新ソース自動選択は遅延の最も低いソースを選び、手動選択が失敗した場合は順にフォールバックします自動選択(推奨)公式ミラーGitHub思拓创联GitHub ミラー更新を確認更新をインストールダウンロードしてインストール強制的に更新を確認現在のチャンネルの最新バージョンを確認し、現在のバージョンより古い場合も確認対象になります更新を確認署名済みの完全なリリースマニフェストだけを確認し、バックグラウンドではダウンロードしません更新サービス未接続このページは、実際の更新確認サービスを将来接続するための v2 設定項目を保持しています前回の確認時刻最後に更新を確認した時刻を表示します更新はまだ確認されていません更新を確認しています最新の状態です新しいバージョン {0} が見つかりました新しいバージョン {0} が見つかりました。完全なインストーラーを選択してください更新操作をキャンセルしました完全なインストーラー {0} をダウンロードしていますインストーラーの整合性を確認していますアプリの更新を準備しています更新をダウンロードしました。インストールを待機しています更新を適用するため再起動していますSECTL 配布では安定版のみ提供されます利用可能な更新ソースがありません現在のシステム、アーキテクチャ、インストール形態に対応する完全なインストーラーがありませんSECTL からバージョンタグが返されませんでした更新メタデータが空です更新メタデータが無効です更新チャンネル {0} にバージョンタグがありません更新マニフェストの署名確認に失敗しました更新マニフェストが無効です更新マニフェストが選択したチャンネルと一致しません内蔵更新公開鍵が無効ですポータブル版に安定版 Launcher がないため、自動展開できません。新しい完全 ZIP を一度ダウンロードしてください完全 ZIP にバージョンディレクトリがありません完全 ZIP にパッケージ識別子がありません完全 ZIP が現在の環境と一致しません対象バージョンのディレクトリが既にあります。再度更新を確認してください完全 ZIP に Launcher がありませんインストーラーのサイズが更新マニフェストと一致しませんインストーラーの SHA-512 確認に失敗しました完全 ZIP のファイル数が安全上限を超えています完全 ZIP に無効なファイルパスがあります完全 ZIP の展開後サイズが安全上限を超えています完全 ZIP にパッケージ外のパスがありますこのインストーラー形式はサポートされていませんシステムインストーラーを起動できませんでした更新マニフェストに不明なインストーラー形式があります +更新設定更新方針自動更新モード更新の確認と通知の頻度を設定しますオフ自動確認して通知自動確認してダウンロード自動確認してインストール更新チャンネル安定版またはプレビュー版を選択します安定版プレビューベータ版開発版更新ソース自動選択は遅延の最も低いソースを選び、手動選択が失敗した場合は順にフォールバックします自動選択(推奨)公式ミラーGitHub思拓创联GitHub ミラー更新を確認更新をインストールダウンロードしてインストール強制的に更新を確認現在のチャンネルの最新バージョンを確認し、現在のバージョンより古い場合も確認対象になります更新を確認署名済みの完全なリリースマニフェストだけを確認し、バックグラウンドではダウンロードしません更新サービス未接続このページは、実際の更新確認サービスを将来接続するための v2 設定項目を保持しています前回の確認時刻最後に更新を確認した時刻を表示します更新はまだ確認されていません更新を確認しています最新の状態です新しいバージョン {0} が見つかりました新しいバージョン {0} が見つかりました。完全なインストーラーを選択してください更新操作をキャンセルしました完全なインストーラー {0} をダウンロードしていますインストーラーの整合性を確認していますアプリの更新を準備しています更新をダウンロードしました。インストールを待機しています更新を適用するため再起動していますSECTL 配布では安定版のみ提供されます利用可能な更新ソースがありません現在のシステム、アーキテクチャ、インストール形態に対応する完全なインストーラーがありませんSECTL からバージョンタグが返されませんでした更新メタデータが空です更新メタデータが無効です更新チャンネル {0} にバージョンタグがありません更新マニフェストの署名確認に失敗しました更新マニフェストが無効です更新マニフェストが選択したチャンネルと一致しません内蔵更新公開鍵が無効ですデータフォルダーが今回の更新で置き換えるバージョンフォルダー内にあるため、更新すると見失います。先に「設定 → 一般 → 保存場所」でデータフォルダーを移動してから、更新を再試行してください。ポータブル版に安定版 Launcher がないため、自動展開できません。新しい完全 ZIP を一度ダウンロードしてください完全 ZIP にバージョンディレクトリがありません完全 ZIP にパッケージ識別子がありません完全 ZIP が現在の環境と一致しません対象バージョンのディレクトリが既にあります。再度更新を確認してください完全 ZIP に Launcher がありませんインストーラーのサイズが更新マニフェストと一致しませんインストーラーの SHA-512 確認に失敗しました完全 ZIP のファイル数が安全上限を超えています完全 ZIP に無効なファイルパスがあります完全 ZIP の展開後サイズが安全上限を超えています完全 ZIP にパッケージ外のパスがありますこのインストーラー形式はサポートされていませんシステムインストーラーを起動できませんでした更新マニフェストに不明なインストーラー形式があります diff --git a/SecRandom/Langs/SettingsPages/Update/Resources.resx b/SecRandom/Langs/SettingsPages/Update/Resources.resx index e490c961b..d4a28ae0d 100644 --- a/SecRandom/Langs/SettingsPages/Update/Resources.resx +++ b/SecRandom/Langs/SettingsPages/Update/Resources.resx @@ -136,6 +136,7 @@ 更新清单与所选通道不匹配 内置更新公钥无效 当前便携版缺少稳定 Launcher,无法自动部署版本目录,请下载一次新的全量 ZIP + 数据目录位于本次更新将要替换的版本目录内,更新会使其失效。请先在“设置 → 通用 → 存储位置”中把数据目录迁移到稳定位置,再重试更新 完整 ZIP 缺少版本目录 完整 ZIP 缺少包形态标记 完整 ZIP 与当前运行环境不匹配 diff --git a/SecRandom/SecRandom.csproj b/SecRandom/SecRandom.csproj index b95129f73..08a38c3c3 100644 --- a/SecRandom/SecRandom.csproj +++ b/SecRandom/SecRandom.csproj @@ -76,6 +76,11 @@ Resources.Designer.cs + + PublicResXFileCodeGenerator + Resources.Designer.cs + + PublicResXFileCodeGenerator Resources.Designer.cs @@ -136,6 +141,11 @@ Resources.Designer.cs + + PublicResXFileCodeGenerator + Resources.Designer.cs + + PublicResXFileCodeGenerator Resources.Designer.cs @@ -285,6 +295,12 @@ Resources.resx + + True + True + Resources.resx + + True True @@ -345,6 +361,12 @@ Resources.resx + + True + True + Resources.resx + + True True diff --git a/SecRandom/Services/Mobile/MobileMediaLibraryService.cs b/SecRandom/Services/Mobile/MobileMediaLibraryService.cs index 2108df45c..46f870542 100644 --- a/SecRandom/Services/Mobile/MobileMediaLibraryService.cs +++ b/SecRandom/Services/Mobile/MobileMediaLibraryService.cs @@ -4,6 +4,7 @@ using SecRandom.Core.Models.AttachedSettings; using SecRandom.Core.Services.Config; using SecRandom.Shared; +using SecRandom.Shared.DataRoot; using SecRandom.Shared.Extensions; namespace SecRandom.Services.Mobile; @@ -245,10 +246,10 @@ private static bool IsImageReferenced( var list = load(name); if (list is null) continue; - if (records(list).Any(record => string.Equals( + if (records(list).Any(record => DataPathReference.RefersToSame( record.GetAttachedObject(Guid.Parse(GlobalConstants.DrawImageAttachedSettings))?.ImagePath, path, - StringComparison.Ordinal))) + Utils.DataRoot))) return true; } return false; diff --git a/SecRandom/Services/Notification/FullscreenNotificationComposer.cs b/SecRandom/Services/Notification/FullscreenNotificationComposer.cs index 5888ac7c4..7bd7adc5b 100644 --- a/SecRandom/Services/Notification/FullscreenNotificationComposer.cs +++ b/SecRandom/Services/Notification/FullscreenNotificationComposer.cs @@ -9,6 +9,8 @@ using SecRandom.Core.Models.SubConfigs; using SecRandom.Core.Services.Config; using SecRandom.Core.Services.Notification; +using SecRandom.Shared; +using SecRandom.Shared.DataRoot; using SecRandom.Shared.Extensions; using SecRandom.Shared.Models.Profile; @@ -187,7 +189,7 @@ private static string DisplayValue(string primary, string fallback) if (settings is not { IsAttachSettingsEnabled: true } || string.IsNullOrWhiteSpace(settings.ImagePath)) return null; - return settings.ImagePath; + return DataPathReference.Resolve(settings.ImagePath, Utils.DataRoot); } catch (Exception) { diff --git a/SecRandom/Services/Updates/UpdateCenterService.cs b/SecRandom/Services/Updates/UpdateCenterService.cs index d8893ca92..5593d9abb 100644 --- a/SecRandom/Services/Updates/UpdateCenterService.cs +++ b/SecRandom/Services/Updates/UpdateCenterService.cs @@ -21,6 +21,7 @@ using SecRandom.Core; using SecRandom.Core.Services.Config; using SecRandom.Shared; +using SecRandom.Shared.DataRoot; using SecRandom.Shared.Updates; using YamlDotNet.Serialization; using UpdateResources = SecRandom.Langs.SettingsPages.Update.Resources; diff --git a/SecRandom/ViewModels/MainPages/LotteryPageViewModel.cs b/SecRandom/ViewModels/MainPages/LotteryPageViewModel.cs index ba590811e..4f3929c00 100644 --- a/SecRandom/ViewModels/MainPages/LotteryPageViewModel.cs +++ b/SecRandom/ViewModels/MainPages/LotteryPageViewModel.cs @@ -39,6 +39,7 @@ using SecRandom.ViewModels; using SecRandom.Views; using SecRandom.Shared; +using SecRandom.Shared.DataRoot; using SecRandom.Shared.Extensions; using SecRandom.Shared.Models.Profile; using SR = SecRandom.Langs.MainPages.Lottery.Resources; @@ -1753,7 +1754,7 @@ private FontFamily BuildResultFontFamily() if (settings is not { IsAttachSettingsEnabled: true } || string.IsNullOrWhiteSpace(settings.ImagePath)) return null; - return DrawImageCache.Load(settings.ImagePath); + return DrawImageCache.Load(DataPathReference.Resolve(settings.ImagePath, Utils.DataRoot)); } private string ToStatusMessage(DrawStatus status) diff --git a/SecRandom/ViewModels/MainPages/QuickDrawPageViewModel.cs b/SecRandom/ViewModels/MainPages/QuickDrawPageViewModel.cs index 8f060f32b..4480ca376 100644 --- a/SecRandom/ViewModels/MainPages/QuickDrawPageViewModel.cs +++ b/SecRandom/ViewModels/MainPages/QuickDrawPageViewModel.cs @@ -34,6 +34,7 @@ using SecRandom.Services.Verification; using SecRandom.ViewModels; using SecRandom.Shared; +using SecRandom.Shared.DataRoot; using SecRandom.Shared.Extensions; using SecRandom.Shared.Models.Profile; @@ -875,7 +876,7 @@ private FontFamily BuildResultFontFamily() if (settings is not { IsAttachSettingsEnabled: true } || string.IsNullOrWhiteSpace(settings.ImagePath)) return null; - return DrawImageCache.Load(settings.ImagePath); + return DrawImageCache.Load(DataPathReference.Resolve(settings.ImagePath, Utils.DataRoot)); } private async void StartCooldown() diff --git a/SecRandom/ViewModels/MainPages/RollCallPageViewModel.cs b/SecRandom/ViewModels/MainPages/RollCallPageViewModel.cs index 10e4cff80..228d93852 100644 --- a/SecRandom/ViewModels/MainPages/RollCallPageViewModel.cs +++ b/SecRandom/ViewModels/MainPages/RollCallPageViewModel.cs @@ -38,6 +38,7 @@ using SecRandom.ViewModels; using SecRandom.Views; using SecRandom.Shared; +using SecRandom.Shared.DataRoot; using SecRandom.Shared.Extensions; using SecRandom.Shared.Models.Profile; using SR = SecRandom.Langs.MainPages.RollCall.Resources; @@ -1532,7 +1533,7 @@ private static string FormatNumericId(string value, int width) if (settings is not { IsAttachSettingsEnabled: true } || string.IsNullOrWhiteSpace(settings.ImagePath)) return null; - return DrawImageCache.Load(settings.ImagePath); + return DrawImageCache.Load(DataPathReference.Resolve(settings.ImagePath, Utils.DataRoot)); } private Task PlayAnimationMusicAsync(string animationMusic) diff --git a/SecRandom/Views/DataRootMigrationWindow.cs b/SecRandom/Views/DataRootMigrationWindow.cs new file mode 100644 index 000000000..e674cbcd6 --- /dev/null +++ b/SecRandom/Views/DataRootMigrationWindow.cs @@ -0,0 +1,263 @@ +using System.Diagnostics; +using Avalonia; +using Avalonia.Controls; +using Avalonia.Controls.ApplicationLifetimes; +using Avalonia.Layout; +using Avalonia.Media; +using Avalonia.Threading; +using SecRandom.Core.Services.DataRoot; +using R = SecRandom.Langs.DataRootMigration.Resources; +using SecRandom.Services.CrashRecovery; +using SecRandom.Shared; +using SecRandom.Shared.DataRoot; + +namespace SecRandom.Views; + +/// +/// The one visible window of a migration launch. It runs before the Host exists, reads the journal written by +/// the settings page, and moves the data root with progress and an explicit retry. The old directory is never +/// deleted here; a successful move only renames it and then relaunches the app on the new root. +/// +internal sealed class DataRootMigrationWindow : Window +{ + private readonly TextBlock _detail; + private readonly IClassicDesktopStyleApplicationLifetime _desktop; + private readonly Button _exit; + private readonly Guid _migrationId; + private readonly ProgressBar _progress; + private readonly Button _restart; + private readonly Button _retry; + private readonly TextBlock _status; + + public DataRootMigrationWindow(Guid migrationId, IClassicDesktopStyleApplicationLifetime desktop) + { + _migrationId = migrationId; + _desktop = desktop; + + Title = R.W_Title; + Width = 560; + SizeToContent = SizeToContent.Height; + CanResize = false; + WindowStartupLocation = WindowStartupLocation.CenterScreen; + ShowInTaskbar = true; + + _status = new TextBlock + { + Text = R.W_Preparing, + FontSize = 16, + FontWeight = FontWeight.SemiBold, + TextWrapping = TextWrapping.Wrap + }; + + _progress = new ProgressBar + { + Minimum = 0, + Maximum = 100, + Height = 6, + IsIndeterminate = true, + Margin = new Thickness(0, 16, 0, 0) + }; + + _detail = new TextBlock + { + TextWrapping = TextWrapping.Wrap, + Margin = new Thickness(0, 12, 0, 0), + Opacity = 0.75, + MaxHeight = 220 + }; + + _retry = new Button + { + Content = R.W_Retry, + IsVisible = false, + Margin = new Thickness(0, 0, 8, 0) + }; + _retry.Click += (_, _) => StartMigration(); + + _restart = new Button + { + Content = R.W_Restart, + IsVisible = false, + IsDefault = true, + Margin = new Thickness(0, 0, 8, 0) + }; + _restart.Click += (_, _) => RestartApplication(); + + _exit = new Button + { + Content = R.W_Exit, + Margin = new Thickness(0, 0, 8, 0) + }; + _exit.Click += (_, _) => Close(); + + var buttons = new StackPanel + { + Orientation = Orientation.Horizontal, + HorizontalAlignment = HorizontalAlignment.Right, + Margin = new Thickness(0, 24, 0, 0) + }; + buttons.Children.Add(_exit); + buttons.Children.Add(_retry); + buttons.Children.Add(_restart); + + Content = new StackPanel + { + Margin = new Thickness(28), + Children = + { + _status, + _progress, + _detail, + buttons + } + }; + + Opened += (_, _) => StartMigration(); + Closing += (_, _) => + { + // The migration window is the only window of this launch, so closing it must also end the process. + Dispatcher.UIThread.Post(() => _desktop.Shutdown()); + }; + } + + private static string AnchorDirectory() + { + var appDirectory = Path.GetFullPath(AppContext.BaseDirectory); + var packageRoot = Utils.PackageRoot; + var isPortable = DataRootPaths.IsPortablePackageLayout(packageRoot, appDirectory); + var anchorPath = DataRootPaths.GetAnchorPath(packageRoot, isPortable); + return Path.GetDirectoryName(anchorPath) ?? packageRoot; + } + + private void StartMigration() + { + _retry.IsVisible = false; + _restart.IsVisible = false; + _progress.IsIndeterminate = true; + _progress.Value = 0; + _status.Text = R.W_Preparing; + _detail.Text = string.Empty; + + var journalPath = DataRootMigrationJournalStore.GetPath(AnchorDirectory()); + var journal = DataRootMigrationJournalStore.Read(journalPath); + if (journal is null || !string.Equals(journal.TransactionId, _migrationId.ToString("N"), + StringComparison.OrdinalIgnoreCase)) + { + _progress.IsVisible = false; + _status.Text = R.W_Failed; + _detail.Text = R.W_JournalMissing; + return; + } + + if (journal.State == DataRootMigrationState.Completed) + { + ShowSuccess(journal.TargetRoot, journal.SourceArchiveRoot, null); + return; + } + + var progress = new Progress(ReportProgress); + _ = Task.Run(() => + { + var engine = new DataRootMigrationEngine(journal, journalPath, AppContext.BaseDirectory); + return engine.Run(progress, CancellationToken.None); + }).ContinueWith(task => Dispatcher.UIThread.Post(() => Finish(task)), TaskScheduler.Default); + } + + private void ReportProgress(DataRootMigrationProgress progress) + { + switch (progress.Phase) + { + case DataRootMigrationPhase.Preparing: + _status.Text = R.W_Preparing; + break; + case DataRootMigrationPhase.Copying: + _status.Text = string.Format(R.W_Copying, progress.CopiedFileCount, progress.TotalFileCount); + _progress.IsIndeterminate = progress.TotalByteCount <= 0; + if (progress.TotalByteCount > 0) + _progress.Value = Math.Clamp(progress.CopiedByteCount * 100.0 / progress.TotalByteCount, 0, 100); + break; + case DataRootMigrationPhase.Verifying: + _status.Text = R.W_Verifying; + break; + case DataRootMigrationPhase.Committing: + _status.Text = R.W_Committing; + break; + case DataRootMigrationPhase.Completed: + _progress.IsIndeterminate = false; + _progress.Value = 100; + break; + case DataRootMigrationPhase.Failed: + _progress.IsVisible = false; + break; + } + } + + private void Finish(Task task) + { + if (task.IsFaulted) + { + _progress.IsVisible = false; + _status.Text = R.W_Failed; + _detail.Text = string.Format(R.W_FailedDetail, + task.Exception?.GetBaseException().Message ?? string.Empty); + _retry.IsVisible = true; + _restart.IsVisible = false; + return; + } + + var result = task.Result; + if (!result.Success) + { + _progress.IsVisible = false; + _status.Text = R.W_Failed; + _detail.Text = string.Format(R.W_FailedDetail, result.Detail ?? string.Empty); + _retry.IsVisible = true; + _restart.IsVisible = false; + return; + } + + ShowSuccess(result.TargetRoot, result.SourceArchiveRoot, result.Warning); + } + + private void ShowSuccess(string targetRoot, string? archiveRoot, string? warning) + { + _status.Text = R.W_Completed; + _progress.IsVisible = true; + _progress.IsIndeterminate = false; + _progress.Value = 100; + + var lines = new List + { + string.Format(R.W_CompletedDetail, targetRoot) + }; + if (!string.IsNullOrWhiteSpace(archiveRoot)) + lines.Add(string.Format(R.W_OldDirectoryKept, archiveRoot)); + if (!string.IsNullOrWhiteSpace(warning)) + lines.Add(warning); + + _detail.Text = string.Join(Environment.NewLine, lines); + _retry.IsVisible = false; + _restart.IsVisible = true; + } + + private void RestartApplication() + { + var startInfo = CrashRecoveryRuntime.CreateRestartStartInfo([]); + try + { + if (startInfo is null) + throw new InvalidOperationException("无法确定应用启动路径。"); + Process.Start(startInfo); + } + catch (Exception exception) + { + _status.Text = R.W_Failed; + _detail.Text = string.Format(R.W_FailedDetail, exception.Message); + _retry.IsVisible = true; + _restart.IsVisible = false; + return; + } + + _desktop.Shutdown(); + } +} \ No newline at end of file diff --git a/SecRandom/Views/FullscreenNotificationWindow.axaml.cs b/SecRandom/Views/FullscreenNotificationWindow.axaml.cs index 2f84ef4ea..d21a5f587 100644 --- a/SecRandom/Views/FullscreenNotificationWindow.axaml.cs +++ b/SecRandom/Views/FullscreenNotificationWindow.axaml.cs @@ -28,6 +28,7 @@ using SecRandom.Platforms.Abstractions; using SecRandom.Services.Notification; using SecRandom.Shared; +using SecRandom.Shared.DataRoot; using SecRandom.Views.Fullscreen; using FullscreenResources = SecRandom.Langs.Fullscreen.Resources; @@ -1140,11 +1141,12 @@ private void ShowStatic( private Border CreateAvatar(FullscreenResultItem item, double size) { Bitmap? bitmap = null; - if (!string.IsNullOrWhiteSpace(item.ImagePath) && File.Exists(item.ImagePath)) + var imagePath = DataPathReference.Resolve(item.ImagePath, Utils.DataRoot); + if (!string.IsNullOrWhiteSpace(imagePath) && File.Exists(imagePath)) { try { - bitmap = new Bitmap(item.ImagePath); + bitmap = new Bitmap(imagePath); } catch (Exception) { diff --git a/SecRandom/Views/SettingsPages/General/StorageSettingsPage.axaml b/SecRandom/Views/SettingsPages/General/StorageSettingsPage.axaml new file mode 100644 index 000000000..0c299e122 --- /dev/null +++ b/SecRandom/Views/SettingsPages/General/StorageSettingsPage.axaml @@ -0,0 +1,124 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + /// + /// Arrangement lists (编排名单) live under config/ but are the one config segment committed as a + /// directory, so they need their own root: otherwise folds every config/ path + /// into config/settings.json and the section would silently disappear on import. + /// + private const string OrchestrationRoot = "config/orchestration"; + private static readonly string[] AllDataRoots = [ - "config/settings.json", "config/device-uuid.json", "list", "history", "TEMP", "proofs", "audio", "CSES", "images", - "Language", "logs", "texts" + "config/settings.json", "config/device-uuid.json", OrchestrationRoot, "list", "history", "TEMP", "proofs", + "audio", "CSES", "images", "Language", "logs", "texts" ]; /// Device-identity path that no restore may commit even if an archive carries it. @@ -564,6 +571,12 @@ private void ValidateCandidate(string staging) ? Directory.EnumerateFiles(Path.Combine(staging, "history"), "*.json", SearchOption.AllDirectories) : []) using (JsonDocument.Parse(File.ReadAllText(path))) { } + + // 编排名单整段是这台机器上的数据:坏 JSON 在导入后只会静默变成"没有名单",所以提交前先解析一次。 + var orchestrationDirectory = Path.Combine(staging, OrchestrationRoot.Replace('/', Path.DirectorySeparatorChar)); + if (Directory.Exists(orchestrationDirectory)) + foreach (var path in Directory.EnumerateFiles(orchestrationDirectory, "*.json", SearchOption.AllDirectories)) + using (JsonDocument.Parse(File.ReadAllText(path))) { } } /// @@ -701,11 +714,17 @@ private static bool IsManagedPath(string path) private static IReadOnlyList GetRoots(IEnumerable paths) { - return paths.Select(NormalizePath).Select(path => path.StartsWith("config/", StringComparison.OrdinalIgnoreCase) - ? path.Equals("config/device-uuid.json", StringComparison.OrdinalIgnoreCase) - ? "config/device-uuid.json" - : "config/settings.json" - : path.Split('/')[0]) + return paths.Select(NormalizePath).Select(path => + { + if (!path.StartsWith("config/", StringComparison.OrdinalIgnoreCase)) + return path.Split('/')[0]; + if (path.Equals(DeviceUuidPath, StringComparison.OrdinalIgnoreCase)) + return DeviceUuidPath; + // 编排列表是 config/ 下唯一按目录提交的段:折叠成 settings.json 会让整段顺序名单在导入时被丢掉。 + if (path.StartsWith(OrchestrationRoot, StringComparison.OrdinalIgnoreCase)) + return OrchestrationRoot; + return "config/settings.json"; + }) .Where(IsManagedPath).Distinct(StringComparer.OrdinalIgnoreCase).ToList(); } diff --git a/SecRandom.Core/Services/CoreRuntimeServiceCollectionExtensions.cs b/SecRandom.Core/Services/CoreRuntimeServiceCollectionExtensions.cs index 320956a35..59a8618f5 100644 --- a/SecRandom.Core/Services/CoreRuntimeServiceCollectionExtensions.cs +++ b/SecRandom.Core/Services/CoreRuntimeServiceCollectionExtensions.cs @@ -5,6 +5,7 @@ using SecRandom.Core.Services.Config; using SecRandom.Core.Services.Draw; using SecRandom.Core.Services.HistoryQuery; +using SecRandom.Core.Services.Orchestration; using SecRandom.Core.Services.Profiles; using SecRandom.Core.Services.Stats; @@ -27,6 +28,8 @@ public static IServiceCollection AddCoreRuntimeServices(this IServiceCollection services.AddSingleton(); services.AddTransient(); services.AddTransient(); + services.AddSingleton(); + services.AddTransient(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); diff --git a/SecRandom.Core/Services/Draw/DrawEngine.Filter.cs b/SecRandom.Core/Services/Draw/DrawEngine.Filter.cs index 9d7fdb3f9..6dd2801ef 100644 --- a/SecRandom.Core/Services/Draw/DrawEngine.Filter.cs +++ b/SecRandom.Core/Services/Draw/DrawEngine.Filter.cs @@ -85,11 +85,15 @@ private static List ApplyAverageGapProtection( if (drawCount > filteredList.Count) throw new RepeatLimitExhaustedException(); - // Average-gap protection is intentionally mandatory for fair draws. It is - // the hard candidate gate; the fair algorithm only ranks this pool later. + // Average-gap protection is the hard candidate gate of the UniformFirst fair mode; the fair algorithm + // only ranks that pool later. RandomFirst keeps the whole roster and moves the exclusion into the + // weight layer as an exact zero, so its pool must not be narrowed here. if (executionPolicy.DrawType != DrawType.Fair) return filteredList; + if (executionPolicy.FairDrawSettings.Mode == FairDrawMode.RandomFirst) + return filteredList; + var countByStudent = filteredList.ToDictionary( s => s, s => historyCache.GetValueOrDefault(s)?.TotalCount ?? 0 diff --git a/SecRandom.Core/Services/Draw/DrawEngine.Orchestration.cs b/SecRandom.Core/Services/Draw/DrawEngine.Orchestration.cs new file mode 100644 index 000000000..f2ff7a00e --- /dev/null +++ b/SecRandom.Core/Services/Draw/DrawEngine.Orchestration.cs @@ -0,0 +1,36 @@ +using SecRandom.Shared.Models.Profile; + +namespace SecRandom.Core.Services.Draw; + +public partial class DrawEngine +{ + /// + /// Per-student history figures for the scheduler: how often each candidate was drawn and when it was last + /// drawn, read through exactly the same course/history-group scope as the fairness weights. + /// + /// + /// The orchestration scheduler needs the raw counts (not only the resulting weights) because a candidate + /// whose weight is zero is not excluded there: the round still has to seat it, and the counts are what order + /// that deferred tail (most-drawn first, then longest-unseen). + /// + public IReadOnlyDictionary GetStudentHistoryFigures( + IReadOnlyList candidates, + string courseName = "", + string? historyGroup = null) + { + ArgumentNullException.ThrowIfNull(candidates); + var pool = candidates.Where(candidate => candidate.IsCandidate).ToList(); + if (pool.Count == 0) + return new Dictionary(); + + var cache = BuildStudentHistoryCache(pool, courseName, historyGroup); + var figures = new Dictionary(cache.Count); + foreach (var pair in cache) + { + if (pair.Key.RecordId == Guid.Empty) + ProfileRecordIdentity.EnsureRecordId(pair.Key); + figures[pair.Key.RecordId] = (pair.Value.TotalCount, pair.Value.LastDrawnTime); + } + return figures; + } +} \ No newline at end of file diff --git a/SecRandom.Core/Services/Draw/DrawEngine.WeightCalculator.cs b/SecRandom.Core/Services/Draw/DrawEngine.WeightCalculator.cs index 316c1cd30..6be0c15d0 100644 --- a/SecRandom.Core/Services/Draw/DrawEngine.WeightCalculator.cs +++ b/SecRandom.Core/Services/Draw/DrawEngine.WeightCalculator.cs @@ -6,10 +6,27 @@ namespace SecRandom.Core.Services.Draw; public partial class DrawEngine { + // Kept for the anonymous audit payload shape only: the unified deficit weight no longer uses + // share debt, dimension horizons, or the uniform random floor. internal const double ShareDebtPersonalHorizonRounds = 2.0; internal const double ShareDebtDimensionHorizonPerPick = 0.8; internal const double ShareDebtRandomFloor = 0.10; + /// + /// The largest lead a candidate may hold over the least-drawn member, in whole draws. Weight falls by one + /// for every draw a candidate is ahead of the minimum, so the least-drawn members always dominate while + /// the tier one draw ahead still keeps a real chance. Reaching this lead makes the weight exactly zero, + /// which is what keeps a 3-vs-0 history from ever appearing: a member two draws ahead can be drawn (to + /// three) only after the minimum has moved to one. + /// + internal const int MaxLeadTiers = 2; + + /// + /// Keeps every positive weight drawable after the fixed-point freeze, so a mathematically tiny weight is + /// never rounded into an unusable zero. It never lifts a real zero: exclusion stays exact. + /// + internal const double MinimumPositiveProbability = 1e-6; + public List> CalculateStudentWeight( List candidates, IReadOnlyDictionary? historyCacheOverride = null, @@ -50,66 +67,62 @@ internal List> CalculateStudentWeight( var counts = candidates .Select(candidate => Math.Max(0, historyCache.GetValueOrDefault(candidate)?.TotalCount ?? 0)) .ToArray(); - var totalDraws = counts.Sum(); - var personalHorizon = ShareDebtPersonalHorizonRounds * candidates.Count; - var personalDebt = counts - .Select(count => Math.Max((totalDraws + personalHorizon) / candidates.Count - count, 0.0)) + var shielded = candidates + .Select((candidate, index) => historyCache.TryGetValue(candidate, out var history) + && IsStudentShielded(history.LastDrawnTime, fairSettings)) .ToArray(); - var debtWeights = personalDebt.ToArray(); - foreach (var selector in GetEnabledDimensionSelectors(fairSettings)) + return CalculateDeficitWeights(candidates, counts, shielded, fairSettings); + } + + /// + /// The one weight function shared by both fair-draw modes: a candidate's weight is the distance to the + /// average tier (floor(mean) + 0.5), so counts above the average drop to exactly zero while the + /// average tier itself keeps half a share. Uniform-first runs it on the average-gap pool and keeps the + /// whole pool drawable; random-first runs it on every eligible candidate and only requires the requested + /// count, which is how a hard candidate gate becomes a zero probability without changing the math. + /// + private static List> CalculateDeficitWeights( + List candidates, + int[] counts, + bool[] shielded, + FairDrawPolicySnapshot fairSettings) + { + var minCount = counts.Length == 0 ? 0 : counts.Min(); + // While somebody is still at zero, cap the lead at one draw: nobody can be drawn a second time before + // everyone has been drawn once. That first full round is the part a class actually watches; only after + // it completes does the wider two-draw ceiling apply and the real randomness show up. + var leadCap = minCount == 0 ? 1 : MaxLeadTiers; + var ceiling = minCount + leadCap; + + var required = fairSettings.Mode == FairDrawMode.UniformFirst + ? candidates.Count + : Math.Clamp(fairSettings.RequiredCount, 1, candidates.Count); + if (counts.Count(count => count < ceiling) < required) { - var labels = candidates.Select(selector).ToArray(); - var labelMembers = labels - .GroupBy(label => label ?? string.Empty, StringComparer.Ordinal) - .ToDictionary(group => group.Key, group => group.Count(), StringComparer.Ordinal); - var labelCounts = labels - .Select((label, index) => (label: label ?? string.Empty, index)) - .GroupBy(item => item.label, StringComparer.Ordinal) - .ToDictionary(group => group.Key, group => group.Sum(item => counts[item.index]), StringComparer.Ordinal); - var horizon = ShareDebtDimensionHorizonPerPick * Math.Max(1, fairSettings.BatchSize); - var dimensionDebt = labelMembers.ToDictionary( - pair => pair.Key, - pair => Math.Max(pair.Value / (double)candidates.Count * (totalDraws + horizon) - - labelCounts.GetValueOrDefault(pair.Key), 0.0), - StringComparer.Ordinal); - - for (var index = 0; index < debtWeights.Length; index++) - debtWeights[index] *= dimensionDebt[labels[index] ?? string.Empty]; + var sortedCounts = counts.OrderBy(count => count).ToArray(); + ceiling = Math.Max(ceiling, sortedCounts[Math.Clamp(required, 1, sortedCounts.Length) - 1] + 1); } - if (debtWeights.Sum() <= 0.0 && personalDebt.Sum() > 0.0) - debtWeights = personalDebt; - var shielded = candidates - .Select((candidate, index) => historyCache.TryGetValue(candidate, out var history) - && IsStudentShielded(history.LastDrawnTime, fairSettings)) + var weights = counts + .Select(count => Math.Max(ceiling - count, 0.0)) .ToArray(); - var activeCount = shielded.Count(value => !value); - var activeWeightSum = debtWeights + var activeWeightSum = weights .Select((weight, index) => shielded[index] ? 0.0 : weight) .Sum(); return candidates.Select((candidate, index) => { - if (shielded[index] || activeCount == 0) + if (shielded[index] || weights[index] <= 0.0) return new WeightedCandidate { Candidate = candidate, Weight = 0.0 }; - var normalized = activeWeightSum > 0.0 - ? debtWeights[index] / activeWeightSum - : 1.0 / activeCount; - var probability = (1.0 - ShareDebtRandomFloor) * normalized + ShareDebtRandomFloor / activeCount; + var probability = activeWeightSum > 0.0 ? weights[index] / activeWeightSum : 0.0; + if (probability > 0.0) + probability = Math.Max(probability, MinimumPositiveProbability); return new WeightedCandidate { Candidate = candidate, Weight = probability }; }).ToList(); } - private static IEnumerable> GetEnabledDimensionSelectors(FairDrawPolicySnapshot fairSettings) - { - if (fairSettings.FairDrawGroup) - yield return student => student.Group; - if (fairSettings.FairDrawGender) - yield return student => student.Gender; - } - private bool IsStudentShielded(DateTime lastDrawnTime) { return IsStudentShielded(lastDrawnTime, FairDrawPolicySnapshot.FromConfig(ConfigData.FairDrawSettings)); diff --git a/SecRandom.Core/Services/Draw/DrawEngine.cs b/SecRandom.Core/Services/Draw/DrawEngine.cs index 4f399856f..9e9f74663 100644 --- a/SecRandom.Core/Services/Draw/DrawEngine.cs +++ b/SecRandom.Core/Services/Draw/DrawEngine.cs @@ -289,7 +289,11 @@ private List> BuildStudentWeightedCandidates( { var algorithm = _rollCallAlgorithms.Resolve(executionPolicy.AlgorithmId ?? (executionPolicy.DrawType == DrawType.Fair ? "builtin.fair" : "builtin.random")); - var fairSettings = executionPolicy.FairDrawSettings with { BatchSize = Math.Max(1, batchSize) }; + var fairSettings = executionPolicy.FairDrawSettings with + { + BatchSize = Math.Max(1, batchSize), + RequiredCount = Math.Max(1, batchSize) + }; return algorithm.BuildCandidates(this, usable, historyCache, fairSettings, courseName) .ToList(); } diff --git a/SecRandom.Core/Services/Draw/DrawModeSelection.cs b/SecRandom.Core/Services/Draw/DrawModeSelection.cs new file mode 100644 index 000000000..c914b8c8c --- /dev/null +++ b/SecRandom.Core/Services/Draw/DrawModeSelection.cs @@ -0,0 +1,94 @@ +using SecRandom.Core.Enums.Configs; +using SecRandom.Core.Models.SubConfigs.Picking; + +namespace SecRandom.Core.Services.Draw; + +/// +/// 「抽取方式」和「抽取模式」的分工:抽取方式回答「谁被抽出来」,抽取模式只回答「重复抽取记录怎么处理」。 +/// +/// +/// +/// 编排抽取没有重复语义——顺序早在抽取前就排定了,重复上限、平均次数保护和公平权重全被绕过—— +/// 所以它不该挂在「抽取模式」这个重复策略下拉里,而是和随机抽取、公平抽取一样出现在「抽取方式」里。 +/// 抽取端读的仍然是 ,这里只负责把「选了编排」这件事 +/// 翻译成那个值,并在退出编排时把重复策略还回去。 +/// +/// +/// 为什么不在选中编排时直接把 DrawMode 覆盖掉就算了:那样用户再改回随机抽取时, +/// 原来的允许重复 / 不重复 / 半重复已经没人记得,半重复的档位会被静默压成不重复。 +/// 所以进入编排前先把它记进 。 +/// +/// +public static class DrawModeSelection +{ + public static bool IsOrchestrated(DrawMode mode) => mode == DrawMode.Orchestrated; + + /// 选中「编排抽取」:记下当前重复策略,再切到编排。 + public static void SelectOrchestrated(IOrchestratedDrawSettings settings) + { + ArgumentNullException.ThrowIfNull(settings); + if (IsOrchestrated(settings.DrawMode)) + return; + + settings.SampledDrawMode = NormalizeSampled(settings.DrawMode); + settings.DrawMode = DrawMode.Orchestrated; + } + + /// 改回随机或公平抽取:把进入编排前的重复策略还回去。 + public static void LeaveOrchestrated(IOrchestratedDrawSettings settings) + { + ArgumentNullException.ThrowIfNull(settings); + if (!IsOrchestrated(settings.DrawMode)) + return; + + settings.DrawMode = NormalizeSampled(settings.SampledDrawMode); + } + + /// + /// 「抽取模式」下拉框当前应该显示的那一档重复策略:编排期间显示进入编排前记住的值, + /// 否则就是正在生效的 DrawMode。 + /// + /// + /// 这个值永远落在允许重复 / 不重复 / 半重复里,所以它适合绑下拉框的 `SelectedIndex` + /// (索引 0..2)。直接把 DrawMode 绑上去是不行的:编排抽取值是 3,下拉只有三项, + /// `SelectedIndex` 会被强制回 -1 再经 TwoWay 写回配置,既清空下拉又把编排状态悄悄丢掉。 + /// + public static DrawMode ResolveRepeatPolicy(IOrchestratedDrawSettings settings) + { + ArgumentNullException.ThrowIfNull(settings); + return IsOrchestrated(settings.DrawMode) + ? NormalizeSampled(settings.SampledDrawMode) + : NormalizeSampled(settings.DrawMode); + } + + /// 用户在「抽取模式」下拉框里换了一档:编排期间只记下来,不把通道从编排里拖出来。 + public static void SetRepeatPolicy(IOrchestratedDrawSettings settings, DrawMode repeatPolicy) + { + ArgumentNullException.ThrowIfNull(settings); + var normalized = NormalizeSampled(repeatPolicy); + settings.SampledDrawMode = normalized; + if (!IsOrchestrated(settings.DrawMode)) + settings.DrawMode = normalized; + } + + /// + /// DrawMode 被外部改写(换抽取方式、导入配置、控制面下发)后,让记住的重复策略跟上它。 + /// 编排期间必须保持原样:那个值就是退出编排时要还回去的档位。 + /// + public static void SynchronizeRepeatPolicy(IOrchestratedDrawSettings settings) + { + ArgumentNullException.ThrowIfNull(settings); + if (!IsOrchestrated(settings.DrawMode)) + settings.SampledDrawMode = NormalizeSampled(settings.DrawMode); + } + + /// + /// 恢复值只能是抽样策略。手改的配置文件、导入的旧存档或控制面下发都可能把它写成 + /// ,那不是一个可恢复的重复策略,退回不重复。 + /// + private static DrawMode NormalizeSampled(DrawMode mode) => mode switch + { + DrawMode.Repeat or DrawMode.NoRepeat or DrawMode.HalfRepeat => mode, + _ => DrawMode.NoRepeat + }; +} \ No newline at end of file diff --git a/SecRandom.Core/Services/Draw/DrawRepeatPolicy.cs b/SecRandom.Core/Services/Draw/DrawRepeatPolicy.cs index 6e2a911a9..ddcf42dc9 100644 --- a/SecRandom.Core/Services/Draw/DrawRepeatPolicy.cs +++ b/SecRandom.Core/Services/Draw/DrawRepeatPolicy.cs @@ -9,6 +9,9 @@ public static class DrawRepeatPolicy DrawMode.Repeat => 0, DrawMode.NoRepeat => 1, DrawMode.HalfRepeat => Math.Max(1, halfRepeat), + // Orchestration replaces the repeat limit: who participates, and how often, is already decided by the + // schedule, so no history-driven limit may silently drop a participant the teacher arranged. + DrawMode.Orchestrated => 0, _ => 1 }; diff --git a/SecRandom.Core/Services/Draw/LotterySession.cs b/SecRandom.Core/Services/Draw/LotterySession.cs index 2813b1dd6..1268a8658 100644 --- a/SecRandom.Core/Services/Draw/LotterySession.cs +++ b/SecRandom.Core/Services/Draw/LotterySession.cs @@ -1,7 +1,9 @@ using SecRandom.Core.Abstraction.Services; +using SecRandom.Core.Enums; using SecRandom.Core.Models.Draw; using SecRandom.Core.Models.SubConfigs.Picking; using SecRandom.Core.Services.Config; +using SecRandom.Core.Services.Profiles; using SecRandom.Core.Services.SimpleMode; using SecRandom.Shared.Models.Profile; @@ -12,7 +14,8 @@ internal sealed class LotterySession( IProfileService profileService, IDrawTemporaryRecordService temporaryRecordService, IDrawCommitService drawCommitService, - DrawEngine drawEngine) : ILotterySession + DrawEngine drawEngine, + IHistoryGroupCatalog historyGroupCatalog) : ILotterySession { private LotterySettingsConfig Settings => configHandler.Data.SimpleModeEnabled ? SimpleModeDefaults.LotterySettings : configHandler.Data.LotterySettings; @@ -47,9 +50,28 @@ public DrawResult DrawOnce() DateTime.Now, 1, GetListName(), - PrizeDrawMethod: (int)Settings.DrawType)); + PrizeDrawMethod: (int)Settings.DrawType, + RecordGroup: ResolveRecordGroup())); return output; } + /// + /// 这条奖品历史该盖的组标记:抽奖有自己的默认记录组,绝不能因为移动端没有组选择器就并进默认组。 + /// + private string ResolveRecordGroup() + { + IReadOnlyList? names = null; + try + { + names = historyGroupCatalog.GetGroupNames(HistoryGroupKind.Lottery); + } + catch (Exception) + { + // 组目录只是书签:读不到只影响「组名是否还存在」的判断,不能让一次抽取因此失败。 + } + + return HistoryGroupScope.ResolveRecordGroup(Settings.HistoryGroup, names); + } + private string GetListName() => profileService.PrizeListConfig?.Name ?? "default"; } diff --git a/SecRandom.Core/Services/Draw/RollCallSession.cs b/SecRandom.Core/Services/Draw/RollCallSession.cs index bbd63df21..b15af509d 100644 --- a/SecRandom.Core/Services/Draw/RollCallSession.cs +++ b/SecRandom.Core/Services/Draw/RollCallSession.cs @@ -4,6 +4,7 @@ using SecRandom.Core.Models.Draw; using SecRandom.Core.Models.SubConfigs.Picking; using SecRandom.Core.Services.Config; +using SecRandom.Core.Services.Profiles; using SecRandom.Core.Services.SimpleMode; using SecRandom.Shared.Models.Profile; @@ -14,7 +15,8 @@ internal sealed class RollCallSession( IProfileService profileService, IDrawTemporaryRecordService temporaryRecordService, IDrawCommitService drawCommitService, - DrawEngine drawEngine) : IRollCallSession + DrawEngine drawEngine, + IHistoryGroupCatalog historyGroupCatalog) : IRollCallSession { /// 简洁模式下隐藏的点名抽取设置按默认值读取。 private RollCallSettingsConfig Settings => configHandler.Data.SimpleModeEnabled @@ -55,9 +57,30 @@ public DrawResult DrawOnce() 1, GetListName(), DrawMethod: (int)drawType, - Weights: weights)); + Weights: weights, + RecordGroup: ResolveRecordGroup())); return output; } + /// + /// 这条历史记录该盖的组标记。移动端点名没有组选择器,读取范围永远是「全部历史」,但写入必须落在 + /// 本通道自己配置的默认记录组上——否则点名、闪抽、抽奖的记录会一起挤进默认组(见 + /// )。 + /// + private string ResolveRecordGroup() + { + IReadOnlyList? names = null; + try + { + names = historyGroupCatalog.GetGroupNames(HistoryGroupKind.RollCall); + } + catch (Exception) + { + // 组目录只是书签:读不到就只影响「组名是否还存在」的判断,不能让一次抽取因此失败。 + } + + return HistoryGroupScope.ResolveRecordGroup(Settings.HistoryGroup, names); + } + private string GetListName() => profileService.StudentListConfig?.Name ?? "default"; } diff --git a/SecRandom.Core/Services/Draw/StudentDrawExecutionPolicy.cs b/SecRandom.Core/Services/Draw/StudentDrawExecutionPolicy.cs index 4d3282cf1..f03212af3 100644 --- a/SecRandom.Core/Services/Draw/StudentDrawExecutionPolicy.cs +++ b/SecRandom.Core/Services/Draw/StudentDrawExecutionPolicy.cs @@ -32,6 +32,19 @@ public sealed record FairDrawPolicySnapshot( /// public int BatchSize { get; init; } = 1; + /// + /// Fair-draw strategy. Defaults to the historical hard average gate so every caller that only supplies + /// the positional fields keeps yesterday's behaviour. + /// + public FairDrawMode Mode { get; init; } = FairDrawMode.UniformFirst; + + /// + /// How many winners the draw has to produce. Only reads it: the + /// zero-probability threshold is relaxed just enough that this many candidates stay drawable, so a + /// multi-pick draw never starves on its own average gate. Public callers keep the single-winner default. + /// + public int RequiredCount { get; init; } = 1; + public static FairDrawPolicySnapshot FromConfig(FairDrawSettingsConfig settings) { return new FairDrawPolicySnapshot( @@ -53,7 +66,10 @@ public static FairDrawPolicySnapshot FromConfig(FairDrawSettingsConfig settings) settings.MaxWeight, settings.GroupWeight, settings.GenderWeight, - settings.TimeWeight); + settings.TimeWeight) + { + Mode = settings.Mode + }; } public static FairDrawPolicySnapshot MobileDesktopDefaultsV1 { get; } = new( diff --git a/SecRandom.Core/Services/Orchestration/OrchestrationOrdering.cs b/SecRandom.Core/Services/Orchestration/OrchestrationOrdering.cs new file mode 100644 index 000000000..5920b95b4 --- /dev/null +++ b/SecRandom.Core/Services/Orchestration/OrchestrationOrdering.cs @@ -0,0 +1,135 @@ +using SecRandom.Core.Interfaces; +using SecRandom.Core.Models.Orchestration; + +namespace SecRandom.Core.Services.Orchestration; + +/// +/// Turns one round's five lists into the concrete draw order for the still-undrawn participants. +/// +/// +/// +/// A round is a queue: whoever comes out leaves the queue and everyone behind moves up one place. +/// That is why 「顺序」 is the round's lineup and not a set of absolute slots — a member scheduled third +/// comes out third (or right after whoever of the first two was postponed), instead of being re-seated +/// third inside the shrinking remainder and therefore never reached by a one-person draw. +/// +/// Resolution order, honouring the rule switches: +/// +/// 排斥 (Exclude) removes the member from every round; 延后 (Defer) removes it from +/// this round only; already-drawn members are removed as well; +/// 必中 (Guarantee) puts this round's guaranteed members in front — internally ordered by the +/// effective weight and then by the order they were added, so a weight still decides who of them goes +/// first; +/// 顺序 (Order) puts the round's queue in front, in queue order; when both switches are off +/// nothing jumps ahead; +/// the rest is a weighted fill over the positive effective weights (weighted sampling without +/// replacement), and a zero weight is not a removal: it merely moves the member behind the weighted +/// ones, most-drawn first, so a round always seats everyone. +/// +/// +/// 必中 and 顺序 are mutually exclusive at the switch level, so at most one of the two front groups is +/// populated. If a hand-edited file still carries both, 必中 wins and the queue seats the remainder — +/// nobody is ever seated twice. +/// +/// +public static class OrchestrationOrdering +{ + public static IReadOnlyList Resolve( + IReadOnlyList candidates, + OrchestrationRound round, + IReadOnlySet alreadyDrawn, + IRandomSource random, + OrchestrationRules rules) + { + ArgumentNullException.ThrowIfNull(candidates); + ArgumentNullException.ThrowIfNull(round); + ArgumentNullException.ThrowIfNull(alreadyDrawn); + ArgumentNullException.ThrowIfNull(random); + ArgumentNullException.ThrowIfNull(rules); + + var skipped = rules.Defer ? round.Skipped.ToHashSet() : []; + var eligible = candidates + .Where(candidate => rules.Exclude is false || !candidate.IsExcluded) + .Where(candidate => !skipped.Contains(candidate.RecordId)) + .Where(candidate => !alreadyDrawn.Contains(candidate.RecordId)) + .GroupBy(candidate => candidate.RecordId) + .Select(group => group.First()) + .ToList(); + + var byRecordId = eligible.ToDictionary(candidate => candidate.RecordId); + + List front; + if (rules.Guarantee && round.Guaranteed.Count > 0) + { + front = round.Guaranteed + .Where(byRecordId.ContainsKey) + .Distinct() + .OrderByDescending(recordId => EffectiveWeight(byRecordId[recordId], round, rules)) + .ToList(); + // OrderByDescending 是稳定排序,权重相同时保持必中名单里的原始次序。 + } + else if (rules.Order && round.Order.Count > 0) + { + front = round.Order.Where(byRecordId.ContainsKey).Distinct().ToList(); + } + else + { + front = []; + } + + var placed = front.ToHashSet(); + var free = eligible.Where(candidate => !placed.Contains(candidate.RecordId)).ToList(); + + // 每轮手动权重是乘数,不改变零集:权重 0 仍然只是"排到后段",而不是把人踢出去。 + var weighted = free.Where(candidate => EffectiveWeight(candidate, round, rules) > 0).ToList(); + var deferred = free.Where(candidate => EffectiveWeight(candidate, round, rules) <= 0).ToList(); + deferred.Sort((left, right) => left.DrawCount != right.DrawCount + ? right.DrawCount.CompareTo(left.DrawCount) + : left.LastDrawn.CompareTo(right.LastDrawn)); + + return front + .Concat(WeightedOrder(weighted, round, rules, random)) + .Concat(deferred.Select(candidate => candidate.RecordId)) + .ToList(); + } + + /// + /// 每轮手动权重只是原始权重的乘数(默认 1,钳在 0..100);它不参与"谁被排除"的判定,关掉权重名单后 + /// 手动值仍留在数据里但完全不参与排序。 + /// + private static double EffectiveWeight( + OrchestrationCandidate candidate, + OrchestrationRound round, + OrchestrationRules rules) + { + var manual = rules.Weight && round.Weights.TryGetValue(candidate.RecordId, out var configured) + ? configured + : 1d; + return Math.Max(0d, candidate.SamplingWeight) * Math.Clamp(manual, 0d, 100d); + } + + private static IEnumerable WeightedOrder( + List pool, + OrchestrationRound round, + OrchestrationRules rules, + IRandomSource random) + { + var remaining = pool.ToList(); + var weights = pool.Select(candidate => EffectiveWeight(candidate, round, rules)).ToList(); + for (var drawn = 0; drawn < pool.Count; drawn++) + { + var total = weights.Sum(); + var target = random.NextDouble() * total; + var index = 0; + while (index < remaining.Count - 1 && target >= weights[index]) + { + target -= weights[index]; + index++; + } + + yield return remaining[index].RecordId; + remaining.RemoveAt(index); + weights.RemoveAt(index); + } + } +} \ No newline at end of file diff --git a/SecRandom.Core/Services/Orchestration/OrchestrationScheduler.cs b/SecRandom.Core/Services/Orchestration/OrchestrationScheduler.cs new file mode 100644 index 000000000..ca8720482 --- /dev/null +++ b/SecRandom.Core/Services/Orchestration/OrchestrationScheduler.cs @@ -0,0 +1,131 @@ +using SecRandom.Core.Interfaces; +using SecRandom.Core.Models.Orchestration; +using SecRandom.Core.Services.Draw; +using SecRandom.Core.Services.Profiles; +using SecRandom.Shared.Models.Profile; + +namespace SecRandom.Core.Services.Orchestration; + +/// +/// Resolves one round of an arranged draw into the concrete order the participants come out in. +/// +/// +/// The weights reuse the configured fair-draw settings (base weight, shield, mode) through +/// , and a per-round manual weight multiplies them. The five +/// rule lists are applied by , which honours +/// : a switched-off list keeps its data but takes no part in the order. +/// +public sealed class OrchestrationScheduler(DrawEngine drawEngine) +{ + public IReadOnlyList OrderRound( + OrchestrationProfile profile, + OrchestrationRound round, + IReadOnlyList participants, + IReadOnlySet alreadyDrawn, + IRandomSource random, + string courseName = "", + string? historyGroup = null) + { + ArgumentNullException.ThrowIfNull(profile); + ArgumentNullException.ThrowIfNull(round); + ArgumentNullException.ThrowIfNull(participants); + ArgumentNullException.ThrowIfNull(alreadyDrawn); + ArgumentNullException.ThrowIfNull(random); + + var pool = participants.Where(candidate => candidate.IsCandidate).ToList(); + if (pool.Count == 0) + return []; + + var weights = drawEngine.CalculateStudentWeight(pool, null, courseName, historyGroup); + var figures = drawEngine.GetStudentHistoryFigures(pool, courseName, historyGroup); + + var candidates = new List(weights.Count); + foreach (var weighted in weights) + { + var student = weighted.Candidate; + var recordId = RecordIdOf(student); + var member = profile.FindMember(recordId); + var figure = figures.TryGetValue(recordId, out var entry) + ? entry + : (Count: 0, LastDrawn: DateTime.MinValue); + // 每轮手动权重由 OrchestrationOrdering 统一乘进来,这里只给公平算法算出的原始权重。 + candidates.Add(new OrchestrationCandidate( + recordId, + Math.Max(0d, weighted.Weight), + figure.Count, + figure.LastDrawn, + member?.IsExcluded == true)); + } + + var ordered = OrchestrationOrdering.Resolve(candidates, round, alreadyDrawn, random, profile.Rules); + var byRecordId = pool + .GroupBy(RecordIdOf) + .ToDictionary(group => group.Key, group => group.First()); + return ordered + .Where(byRecordId.ContainsKey) + .Select(recordId => byRecordId[recordId]) + .ToList(); + } + + private static Guid RecordIdOf(Student student) + { + if (student.RecordId == Guid.Empty) + ProfileRecordIdentity.EnsureRecordId(student); + return student.RecordId; + } + + /// + /// Prize-side counterpart of the student OrderRound overload. + /// + /// + /// A prize pool has no fair-draw weighting: the pool's own is the base weight and the + /// per-round manual weight multiplies it, so an unconfigured round keeps the pool's existing proportions. + /// 必中 and 顺序 apply the same way, and a postponed prize is skipped for that round only. + /// + public IReadOnlyList OrderRound( + OrchestrationProfile profile, + OrchestrationRound round, + IReadOnlyList participants, + IReadOnlyDictionary drawnCounts, + IRandomSource random) + { + ArgumentNullException.ThrowIfNull(profile); + ArgumentNullException.ThrowIfNull(round); + ArgumentNullException.ThrowIfNull(participants); + ArgumentNullException.ThrowIfNull(drawnCounts); + ArgumentNullException.ThrowIfNull(random); + + var pool = participants.Where(candidate => candidate.IsCandidate).ToList(); + if (pool.Count == 0) + return []; + + var candidates = new List(pool.Count); + foreach (var prize in pool) + { + var recordId = RecordIdOf(prize); + var member = profile.FindMember(recordId); + candidates.Add(new OrchestrationCandidate( + recordId, + Math.Max(0d, prize.Weight), + drawnCounts.GetValueOrDefault(recordId), + DateTime.MinValue, + member?.IsExcluded == true)); + } + + var ordered = OrchestrationOrdering.Resolve(candidates, round, new HashSet(), random, profile.Rules); + var byRecordId = pool + .GroupBy(RecordIdOf) + .ToDictionary(group => group.Key, group => group.First()); + return ordered + .Where(byRecordId.ContainsKey) + .Select(recordId => byRecordId[recordId]) + .ToList(); + } + + private static Guid RecordIdOf(Prize prize) + { + if (prize.RecordId == Guid.Empty) + ProfileRecordIdentity.EnsureRecordId(prize); + return prize.RecordId; + } +} \ No newline at end of file diff --git a/SecRandom.Core/Services/Orchestration/OrchestrationStore.cs b/SecRandom.Core/Services/Orchestration/OrchestrationStore.cs new file mode 100644 index 000000000..9ac6fa210 --- /dev/null +++ b/SecRandom.Core/Services/Orchestration/OrchestrationStore.cs @@ -0,0 +1,262 @@ +using System.Text.Json; +using SecRandom.Core.Models.Orchestration; +using SecRandom.Shared; + +namespace SecRandom.Core.Services.Orchestration; + +/// +/// File-backed store for arranged draw lists. One JSON per profile plus one runtime cursor per profile. +/// +/// +/// The profile and its runtime live in different files on purpose: the settings page rewrites the profile while +/// a draw advances the cursor, so the two must never overwrite each other. Every write is a temporary file plus +/// an atomic replace, matching FileConfigService.SaveConfig. +/// +public interface IOrchestrationStore +{ + IReadOnlyList LoadAll(); + + OrchestrationProfile? Load(string id); + + void Save(OrchestrationProfile profile); + + void Delete(string id); + + /// Reads the cursor of , clamped into that profile's round range. + OrchestrationRuntime GetRuntime(OrchestrationProfile profile); + + void SaveRuntime(OrchestrationRuntime runtime); + + IReadOnlyList FindActive(OrchestrationTarget target, string listName); +} + +public sealed class OrchestrationStore : IOrchestrationStore +{ + private static readonly JsonSerializerOptions JsonOptions = new() { WriteIndented = true }; + + public IReadOnlyList LoadAll() + { + var directory = ProfileDirectory(); + if (!Directory.Exists(directory)) + return []; + + var profiles = new List(); + foreach (var path in Directory.EnumerateFiles(directory, "*.json")) + { + var profile = ReadProfile(path); + if (profile is not null) + profiles.Add(profile); + } + + profiles.Sort((left, right) => + { + var byTarget = left.Target.CompareTo(right.Target); + if (byTarget != 0) + return byTarget; + var byList = string.Compare(left.SourceListName, right.SourceListName, StringComparison.CurrentCulture); + return byList != 0 ? byList : string.Compare(left.Name, right.Name, StringComparison.CurrentCulture); + }); + return profiles; + } + + public OrchestrationProfile? Load(string id) + { + if (!IsValidId(id)) + return null; + var path = ProfilePath(id); + return File.Exists(path) ? ReadProfile(path) : null; + } + + public void Save(OrchestrationProfile profile) + { + ArgumentNullException.ThrowIfNull(profile); + if (!IsValidId(profile.Id)) + throw new ArgumentException("An orchestration profile needs a Guid-based id.", nameof(profile)); + + Normalize(profile, migrateLegacyPins: true); + WriteAtomic(ProfilePath(profile.Id), JsonSerializer.Serialize(profile, JsonOptions)); + } + + /// + /// Brings a profile into the current shape: clamps the round count, normalizes every round's four lists, and + /// drops entries for members that no longer exist. Called before every write and after every read, so a + /// hand-edited file can never leave a round pointing at a removed record. + /// + /// Profile to normalize in place. + /// + /// Whether format-1 「第几个抽中」 pins should be folded into the round queue. Pass true on write, + /// because a written file must never carry the legacy property again. + /// + public static void Normalize(OrchestrationProfile profile, bool migrateLegacyPins = true) + { + ArgumentNullException.ThrowIfNull(profile); + + profile.Rules ??= new OrchestrationRules(); + profile.Members ??= []; + profile.Rounds ??= []; + profile.RoundCount = Math.Clamp(profile.RoundCount, 1, OrchestrationProfile.MaxRounds); + profile.Rounds.RemoveAll(round => round.Index is < 1 or > OrchestrationProfile.MaxRounds); + profile.Rounds.Sort((left, right) => left.Index.CompareTo(right.Index)); + + var memberIds = profile.Members.Select(member => member.RecordId).ToHashSet(); + foreach (var round in profile.Rounds) + { + round.Order ??= []; + round.Skipped ??= []; + round.Guaranteed ??= []; + round.Weights ??= []; + + if (migrateLegacyPins && round.LegacyPins is { Count: > 0 }) + round.Order = MergeLegacyPins(round); + + round.LegacyPins = null; + round.Order = KeepKnown(round.Order, memberIds); + round.Skipped = KeepKnown(round.Skipped, memberIds); + round.Guaranteed = KeepKnown(round.Guaranteed, memberIds); + foreach (var recordId in round.Weights.Keys.Where(key => !memberIds.Contains(key)).ToList()) + round.Weights.Remove(recordId); + } + + profile.FormatVersion = OrchestrationProfile.CurrentFormatVersion; + } + + /// + /// Folds format-1 pins into the round queue: the pinned members first, in pin order, then whatever the old + /// order copy already held. A pinned member used to be seated at an absolute slot in the shrinking + /// remainder, which is exactly what the queue replaced, so the position number itself is not preserved — + /// only the relative order it expressed. + /// + private static List MergeLegacyPins(OrchestrationRound round) + { + var seen = new HashSet(); + var merged = new List(); + foreach (var recordId in round.LegacyPins! + .Where(pin => pin.Position >= 1) + .OrderBy(pin => pin.Position) + .Select(pin => pin.RecordId)) + if (seen.Add(recordId)) + merged.Add(recordId); + + foreach (var recordId in round.Order) + if (seen.Add(recordId)) + merged.Add(recordId); + + return merged; + } + + private static List KeepKnown(IEnumerable recordIds, IReadOnlySet memberIds) + { + var seen = new HashSet(); + var kept = new List(); + foreach (var recordId in recordIds) + if (memberIds.Contains(recordId) && seen.Add(recordId)) + kept.Add(recordId); + return kept; + } + + public void Delete(string id) + { + if (!IsValidId(id)) + return; + SafeDelete(ProfilePath(id)); + SafeDelete(RuntimePath(id)); + } + + public OrchestrationRuntime GetRuntime(OrchestrationProfile profile) + { + ArgumentNullException.ThrowIfNull(profile); + var path = RuntimePath(profile.Id); + OrchestrationRuntime? runtime = null; + if (File.Exists(path)) + { + try + { + runtime = JsonSerializer.Deserialize(File.ReadAllText(path), JsonOptions); + } + catch (JsonException) + { + // A damaged cursor only costs one round; the schedule itself stays valid. + runtime = null; + } + } + + return new OrchestrationRuntime + { + ProfileId = profile.Id, + Round = Math.Clamp(runtime?.Round ?? 1, 1, profile.EffectiveRoundCount), + UpdatedAt = runtime?.UpdatedAt ?? default + }; + } + + public void SaveRuntime(OrchestrationRuntime runtime) + { + ArgumentNullException.ThrowIfNull(runtime); + if (!IsValidId(runtime.ProfileId)) + throw new ArgumentException("An orchestration runtime needs a Guid-based profile id.", nameof(runtime)); + + runtime.UpdatedAt = DateTime.UtcNow; + WriteAtomic(RuntimePath(runtime.ProfileId), JsonSerializer.Serialize(runtime, JsonOptions)); + } + + public IReadOnlyList FindActive(OrchestrationTarget target, string listName) => + LoadAll() + .Where(profile => profile.IsActive + && profile.Target == target + && (string.IsNullOrWhiteSpace(listName) + || string.Equals(profile.SourceListName, listName, StringComparison.Ordinal))) + .ToList(); + + public static string NewId() => Guid.NewGuid().ToString("N"); + + private static string ProfileDirectory() => Utils.GetFilePath("config", "orchestration"); + + private static string ProfilePath(string id) => + Utils.GetFilePath("config", "orchestration", $"{id}.json"); + + private static string RuntimePath(string id) => + Utils.GetFilePath("config", "orchestration", "runtime", $"{id}.json"); + + private static bool IsValidId(string? id) => + !string.IsNullOrWhiteSpace(id) && Guid.TryParseExact(id, "N", out _); + + private static OrchestrationProfile? ReadProfile(string path) + { + try + { + var profile = JsonSerializer.Deserialize(File.ReadAllText(path), JsonOptions); + if (profile is null) + return null; + + // The file name is the identity when a hand-edited file lost its id; a file whose name is not a + // profile id was never ours, so ignore it instead of inventing an identity for it. + if (!IsValidId(profile.Id)) + profile.Id = Path.GetFileNameWithoutExtension(path); + Normalize(profile); + return profile; + } + catch (Exception exception) when (exception is JsonException or IOException or UnauthorizedAccessException) + { + return null; + } + } + + private static void WriteAtomic(string path, string json) + { + var temporaryPath = $"{path}.{Guid.NewGuid():N}.tmp"; + File.WriteAllText(temporaryPath, json); + File.Move(temporaryPath, path, overwrite: true); + } + + private static void SafeDelete(string path) + { + try + { + if (File.Exists(path)) + File.Delete(path); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + // A leftover file is harmless: the next Save overwrites it. + } + } +} \ No newline at end of file diff --git a/SecRandom.Core/Services/Orchestration/OrchestrationVerification.cs b/SecRandom.Core/Services/Orchestration/OrchestrationVerification.cs new file mode 100644 index 000000000..436257541 --- /dev/null +++ b/SecRandom.Core/Services/Orchestration/OrchestrationVerification.cs @@ -0,0 +1,219 @@ +using System.Text.Json; +using SecRandom.Core.Models.Orchestration; +using SecRandom.Core.Models.Verification; +using SecRandom.Shared.Models.Profile; +using VerificationDrawKind = SecRandom.Shared.Models.Verification.VerificationDrawKind; + +namespace SecRandom.Core.Services.Orchestration; + +/// +/// Builds the v3.6.0 verification input for a draw whose order was arranged in advance. +/// +/// +/// +/// The sampled entry points in DrawEngine refuse an orchestrated draw on purpose, because routing it +/// through the weighted pool would produce a proof that replays as a random draw. Here the order is +/// the commitment: every candidate carries its 1-based position in the weight slot, the sampler consumes no +/// random material, and the replay returns exactly those candidates in exactly that order. +/// +/// +/// The anonymous audit payload declares the mode (repeatMode = "orchestrated") and the round counters +/// only. It never carries the schedule, the positions, the names, or the per-round weights: the service +/// replays positions out of the signed payload, and the fair.sectl.cn allow-list rejects everything else. +/// +/// +public static class OrchestrationVerification +{ + public const string AuditOperationStudent = "student"; + public const string AuditOperationPrize = "prize"; + + public static VerificationDrawInput CreateStudentInput( + IReadOnlyList ordered, + int round, + int roundCount, + IReadOnlyDictionary? history = null, + string rosterDigest = "", + string courseName = "", + string? historyGroup = null) + { + ArgumentNullException.ThrowIfNull(ordered); + EnsureOrder(ordered); + var (safeRound, safeRoundCount) = NormalizeRound(round, roundCount); + + var candidates = new List(ordered.Count); + for (var index = 0; index < ordered.Count; index++) + { + var student = ordered[index]; + var recordId = student.RecordId != Guid.Empty + ? student.RecordId + : throw new ArgumentException("Every scheduled student needs a stable RecordId.", nameof(ordered)); + candidates.Add(new VerificationCandidate(recordId, 0, index + 1, false)); + } + + var audit = CreateAuditPayload( + AuditOperationStudent, + candidates, + history, + new + { + fairDraw = false, + algorithmProfile = VerificationAlgorithmProfile.StudentOrchestrated.ToString(), + repeatMode = "orchestrated", + orchestration = new { round = safeRound, roundCount = safeRoundCount }, + historyScope = HistoryScopeName(courseName, historyGroup) + }, + rosterDigest); + + return new VerificationDrawInput + { + Kind = VerificationDrawKind.Student, + SamplingMode = VerificationSamplingMode.SequentialOrder, + AlgorithmProfile = VerificationAlgorithmProfile.StudentOrchestrated, + Count = ordered.Count, + Candidates = candidates, + AuditPayload = audit, + DrawModeToken = "orchestrated", + HistoryScope = HistoryScopeName(courseName, historyGroup), + OrchestrationRound = safeRound, + OrchestrationRoundCount = safeRoundCount + }; + } + + public static VerificationDrawInput CreatePrizeInput( + IReadOnlyList ordered, + int round, + int roundCount, + IReadOnlyDictionary? history = null, + string rosterDigest = "") + { + ArgumentNullException.ThrowIfNull(ordered); + EnsureOrder(ordered); + var (safeRound, safeRoundCount) = NormalizeRound(round, roundCount); + + var candidates = new List(ordered.Count); + for (var index = 0; index < ordered.Count; index++) + { + var prize = ordered[index]; + var recordId = prize.RecordId != Guid.Empty + ? prize.RecordId + : throw new ArgumentException("Every scheduled prize needs a stable RecordId.", nameof(ordered)); + candidates.Add(new VerificationCandidate(recordId, 0, index + 1, false)); + } + + var audit = CreateAuditPayload( + AuditOperationPrize, + candidates, + history, + new + { + samplingAlgorithm = "sequential-order", + inventoryEntriesEqualWeight = false, + internalRulesRequireWeightedFallback = false, + algorithmProfile = VerificationAlgorithmProfile.LotteryOrchestrated.ToString(), + lotteryMode = "pan", + repeatMode = "orchestrated", + orchestration = new { round = safeRound, roundCount = safeRoundCount } + }, + rosterDigest); + + return new VerificationDrawInput + { + Kind = VerificationDrawKind.Prize, + SamplingMode = VerificationSamplingMode.SequentialOrder, + AlgorithmProfile = VerificationAlgorithmProfile.LotteryOrchestrated, + Count = ordered.Count, + Candidates = candidates, + AuditPayload = audit, + DrawModeToken = "orchestrated", + HistoryScope = "global", + OrchestrationRound = safeRound, + OrchestrationRoundCount = safeRoundCount + }; + } + + /// + /// The scheduled order must be dense and unique, because the position itself is the evidence: a gapped or + /// repeated position would replay as a different draw than the one the teacher saw. + /// + private static void EnsureOrder(IReadOnlyList ordered) + { + if (ordered.Count == 0) + throw new ArgumentException("An orchestrated draw needs at least one participant.", nameof(ordered)); + if (ordered.Count > 10_000) + throw new ArgumentOutOfRangeException(nameof(ordered), "An orchestrated draw commits at most 10000 positions."); + } + + private static (int Round, int RoundCount) NormalizeRound(int round, int roundCount) + { + var rounds = Math.Clamp(roundCount, 1, OrchestrationProfile.MaxRounds); + return (Math.Clamp(round, 1, rounds), rounds); + } + + // Midnight UTC of the day the draw happened on; see the sampled audit payload for why the clock time is dropped. + private static DateTime CoarsenLastDrawn(DateTime value) => + DateTime.SpecifyKind(value.ToUniversalTime().Date, DateTimeKind.Utc); + + private static byte[] CreateAuditPayload( + string operation, + IReadOnlyList candidates, + IReadOnlyDictionary? history, + object fairness, + string rosterDigest) + { + var ordered = candidates + .OrderBy(candidate => candidate.RecordId.ToString("N"), StringComparer.Ordinal) + .ThenBy(candidate => candidate.OccurrenceIndex) + .Select((candidate, index) => + { + var figures = history is not null && history.TryGetValue(candidate.RecordId, out var entry) + ? entry + : ((int Count, DateTime? LastDrawn))(0, null); + return new + { + index, + recordId = candidate.RecordId, + // Same key the sampled audit uses: the server allow-lists `OccurrenceIndex`, and an audit payload + // is hashed into the proof commitment, so a stray key name makes the whole proof unverifiable. + candidate.OccurrenceIndex, + candidate.WeightMicros, + candidate.IsGuaranteed, + internalSettingApplied = false, + internalProbability = (double?)null, + historyCount = figures.Count, + // Same day-precision rule as the sampled student/prize audit: the exact last-drawn instant is a + // behavioural fingerprint, the day is the part the audit question actually needs. + lastDrawnUtc = figures.LastDrawn is { } lastDrawn + ? (DateTime?)CoarsenLastDrawn(lastDrawn) + : null + }; + }) + .ToArray(); + + return JsonSerializer.SerializeToUtf8Bytes(new + { + format = "secrandom-anonymous-audit/v2", + operation, + requestedCount = candidates.Count, + candidateCount = ordered.Length, + internalSettingsApplied = false, + internalCandidateCount = 0, + internalExcludedCandidateCount = 0, + fairness, + rosterDigest = string.IsNullOrWhiteSpace(rosterDigest) ? null : rosterDigest, + candidates = ordered + }); + } + + /// + /// Names which slice of profile history the counts came from; the group and course names themselves never + /// leave the device because both are user-typed text that can carry a class or a person's name. + /// + private static string HistoryScopeName(string courseName, string? historyGroup) => + (string.IsNullOrWhiteSpace(courseName), historyGroup is null) switch + { + (true, true) => "global", + (false, true) => "course", + (true, false) => "history-group", + _ => "course-and-history-group" + }; +} \ No newline at end of file diff --git a/SecRandom/Langs/SettingsPages/Picking/Resources.Designer.cs b/SecRandom/Langs/SettingsPages/Picking/Resources.Designer.cs index b38c350b2..5119e8a6e 100644 --- a/SecRandom/Langs/SettingsPages/Picking/Resources.Designer.cs +++ b/SecRandom/Langs/SettingsPages/Picking/Resources.Designer.cs @@ -1,2008 +1,3277 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace SecRandom.Langs.SettingsPages.Picking { - using System; - - - /// - /// A strongly-typed resource class, for looking up localized strings, etc. - /// - // This class was auto-generated by the StronglyTypedResourceBuilder - // class via a tool like ResGen or Visual Studio. - // To add or remove a member, edit your .ResX file then rerun ResGen - // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - public class Resources { - - private static global::System.Resources.ResourceManager resourceMan; - - private static global::System.Globalization.CultureInfo resourceCulture; - - [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - internal Resources() { - } - - /// - /// Returns the cached ResourceManager instance used by this class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - public static global::System.Resources.ResourceManager ResourceManager { - get { - if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("SecRandom.Langs.SettingsPages.Picking.Resources", typeof(Resources).Assembly); - resourceMan = temp; - } - return resourceMan; - } - } - - /// - /// Overrides the current thread's CurrentUICulture property for all - /// resource lookups using this strongly typed resource class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - public static global::System.Globalization.CultureInfo Culture { - get { - return resourceCulture; - } - set { - resourceCulture = value; - } - } - - /// - /// Looks up a localized string similar to 启用覆盖. - /// - public static string C_EnableOverride { - get { - return ResourceManager.GetString("C_EnableOverride", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 淡入. - /// - public static string C_FadeIn { - get { - return ResourceManager.GetString("C_FadeIn", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 淡出. - /// - public static string C_FadeOut { - get { - return ResourceManager.GetString("C_FadeOut", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 直接轮换. - /// - public static string O_AnimationDirectRotate { - get { - return ResourceManager.GetString("O_AnimationDirectRotate", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 淡入上浮. - /// - public static string O_AnimationFadeFloat { - get { - return ResourceManager.GetString("O_AnimationFadeFloat", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 左右晃动. - /// - public static string O_AnimationHorizontalShake { - get { - return ResourceManager.GetString("O_AnimationHorizontalShake", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 自动播放. - /// - public static string O_AutoPlay { - get { - return ResourceManager.GetString("O_AutoPlay", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 编号和姓名. - /// - public static string O_Both { - get { - return ResourceManager.GetString("O_Both", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 下方. - /// - public static string O_Bottom { - get { - return ResourceManager.GetString("O_Bottom", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 卡片. - /// - public static string O_Card { - get { - return ResourceManager.GetString("O_Card", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 手动清除. - /// - public static string O_Cleared { - get { - return ResourceManager.GetString("O_Cleared", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 按剩余数量. - /// - public static string O_Count { - get { - return ResourceManager.GetString("O_Count", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 自定义. - /// - public static string O_Custom { - get { - return ResourceManager.GetString("O_Custom", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 默认. - /// - public static string O_Default { - get { - return ResourceManager.GetString("O_Default", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 公平抽取. - /// - public static string O_Fair { - get { - return ResourceManager.GetString("O_Fair", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 固定颜色. - /// - public static string O_FixedColor { - get { - return ResourceManager.GetString("O_FixedColor", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 跟随全局. - /// - public static string O_FollowGlobal { - get { - return ResourceManager.GetString("O_FollowGlobal", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 半重复. - /// - public static string O_HalfRepeat { - get { - return ResourceManager.GetString("O_HalfRepeat", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 仅编号. - /// - public static string O_Id { - get { - return ResourceManager.GetString("O_Id", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 左侧. - /// - public static string O_Left { - get { - return ResourceManager.GetString("O_Left", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 手动停止. - /// - public static string O_ManualStop { - get { - return ResourceManager.GetString("O_ManualStop", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 外部文件:{0}. - /// - public static string O_MusicExternal { - get { - return ResourceManager.GetString("O_MusicExternal", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 不可用:{0}. - /// - public static string O_MusicUnavailable { - get { - return ResourceManager.GetString("O_MusicUnavailable", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 仅姓名. - /// - public static string O_Name { - get { - return ResourceManager.GetString("O_Name", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 无动画. - /// - public static string O_NoAnimation { - get { - return ResourceManager.GetString("O_NoAnimation", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 无. - /// - public static string O_NoColor { - get { - return ResourceManager.GetString("O_NoColor", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 不开启音乐. - /// - public static string O_NoMusic { - get { - return ResourceManager.GetString("O_NoMusic", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 不重复. - /// - public static string O_NoRepeat { - get { - return ResourceManager.GetString("O_NoRepeat", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 按奖盘. - /// - public static string O_Pan { - get { - return ResourceManager.GetString("O_Pan", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 奖品/小组. - /// - public static string O_PrizeBreakGroup { - get { - return ResourceManager.GetString("O_PrizeBreakGroup", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 奖品/小组/姓名. - /// - public static string O_PrizeBreakGroupBreakName { - get { - return ResourceManager.GetString("O_PrizeBreakGroupBreakName", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 奖品/小组-姓名. - /// - public static string O_PrizeBreakGroupHyphenName { - get { - return ResourceManager.GetString("O_PrizeBreakGroupHyphenName", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 奖品/姓名. - /// - public static string O_PrizeBreakName { - get { - return ResourceManager.GetString("O_PrizeBreakName", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 奖品-小组. - /// - public static string O_PrizeHyphenGroup { - get { - return ResourceManager.GetString("O_PrizeHyphenGroup", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 奖品-小组-姓名. - /// - public static string O_PrizeHyphenGroupHyphenName { - get { - return ResourceManager.GetString("O_PrizeHyphenGroupHyphenName", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 奖品-姓名. - /// - public static string O_PrizeHyphenName { - get { - return ResourceManager.GetString("O_PrizeHyphenName", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 序号 奖品/分组-名称. - /// - public static string O_PrizeIdPrizeBreakGroupHyphenMember { - get { - return ResourceManager.GetString("O_PrizeIdPrizeBreakGroupHyphenMember", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 随机抽取. - /// - public static string O_Random { - get { - return ResourceManager.GetString("O_Random", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 随机. - /// - public static string O_RandomColor { - get { - return ResourceManager.GetString("O_RandomColor", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 随机播放. - /// - public static string O_RandomMusic { - get { - return ResourceManager.GetString("O_RandomMusic", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 允许重复. - /// - public static string O_Repeat { - get { - return ResourceManager.GetString("O_Repeat", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 重启后清除. - /// - public static string O_Restarted { - get { - return ResourceManager.GetString("O_Restarted", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 右侧. - /// - public static string O_Right { - get { - return ResourceManager.GetString("O_Right", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 上方. - /// - public static string O_Top { - get { - return ResourceManager.GetString("O_Top", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 默认抽取设置. - /// - public static string Page_Default { - get { - return ResourceManager.GetString("Page_Default", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 抽奖抽取设置. - /// - public static string Page_Lottery { - get { - return ResourceManager.GetString("Page_Lottery", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 闪抽抽取设置. - /// - public static string Page_QuickDraw { - get { - return ResourceManager.GetString("Page_QuickDraw", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 点名抽取设置. - /// - public static string Page_RollCall { - get { - return ResourceManager.GetString("Page_RollCall", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 动画模式. - /// - public static string S_Animation { - get { - return ResourceManager.GetString("S_Animation", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 设置抽取动画播放方式. - /// - public static string S_Animation_D { - get { - return ResourceManager.GetString("S_Animation_D", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 动画间隔. - /// - public static string S_AnimationInterval { - get { - return ResourceManager.GetString("S_AnimationInterval", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 抽取动画每次切换的间隔(毫秒). - /// - public static string S_AnimationInterval_D { - get { - return ResourceManager.GetString("S_AnimationInterval_D", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 动画音乐. - /// - public static string S_AnimationMusic { - get { - return ResourceManager.GetString("S_AnimationMusic", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 选择抽取动画播放时使用的音乐。. - /// - public static string S_AnimationMusic_D { - get { - return ResourceManager.GetString("S_AnimationMusic_D", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 循环播放动画音乐. - /// - public static string S_AnimationMusicLoop { - get { - return ResourceManager.GetString("S_AnimationMusicLoop", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 动画持续期间重复播放动画音乐。. - /// - public static string S_AnimationMusicLoop_D { - get { - return ResourceManager.GetString("S_AnimationMusicLoop_D", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 动画音乐淡入和淡出. - /// - public static string S_AnimationMusicFade { - get { - return ResourceManager.GetString("S_AnimationMusicFade", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 上方滑块控制淡入,下方滑块控制淡出,单位为毫秒。. - /// - public static string S_AnimationMusicFade_D { - get { - return ResourceManager.GetString("S_AnimationMusicFade_D", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 动画音乐音量. - /// - public static string S_AnimationMusicVolume { - get { - return ResourceManager.GetString("S_AnimationMusicVolume", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 设置抽取动画音乐的音量。. - /// - public static string S_AnimationMusicVolume_D { - get { - return ResourceManager.GetString("S_AnimationMusicVolume_D", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 动画样式. - /// - public static string S_AnimationStyle { - get { - return ResourceManager.GetString("S_AnimationStyle", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 设置抽取过程和最终定格时使用的统一动画效果. - /// - public static string S_AnimationStyle_D { - get { - return ResourceManager.GetString("S_AnimationStyle_D", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 自动播放次数. - /// - public static string S_AutoplayCount { - get { - return ResourceManager.GetString("S_AutoplayCount", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 自动播放模式下滚动候选结果的次数. - /// - public static string S_AutoplayCount_D { - get { - return ResourceManager.GetString("S_AutoplayCount_D", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 清除记录. - /// - public static string S_ClearRecord { - get { - return ResourceManager.GetString("S_ClearRecord", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 控制抽取记录何时清除. - /// - public static string S_ClearRecord_D { - get { - return ResourceManager.GetString("S_ClearRecord_D", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 颜色主题. - /// - public static string S_ColorTheme { - get { - return ResourceManager.GetString("S_ColorTheme", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 设置抽取动画和结果颜色来源. - /// - public static string S_ColorTheme_D { - get { - return ResourceManager.GetString("S_ColorTheme_D", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 自定义字体. - /// - public static string S_CustomFont { - get { - return ResourceManager.GetString("S_CustomFont", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 字体族名称,留空时使用默认字体. - /// - public static string S_CustomFont_D { - get { - return ResourceManager.GetString("S_CustomFont_D", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 默认抽取名单. - /// - public static string S_DefaultClass { - get { - return ResourceManager.GetString("S_DefaultClass", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 打开页面或执行闪抽时默认使用的名单. - /// - public static string S_DefaultClass_D { - get { - return ResourceManager.GetString("S_DefaultClass_D", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 默认抽奖名单. - /// - public static string S_DefaultPool { - get { - return ResourceManager.GetString("S_DefaultPool", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 打开抽奖页时默认使用的奖池. - /// - public static string S_DefaultPool_D { - get { - return ResourceManager.GetString("S_DefaultPool_D", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 不使用名单. - /// - public static string O_NoList { - get { - return ResourceManager.GetString("O_NoList", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 点击后禁用时间. - /// - public static string S_DisableAfterClick { - get { - return ResourceManager.GetString("S_DisableAfterClick", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 点击一次闪抽后禁用按钮的秒数. - /// - public static string S_DisableAfterClick_D { - get { - return ResourceManager.GetString("S_DisableAfterClick_D", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 显示抽取中状态. - /// - public static string S_ShowDrawingStatus { - get { - return ResourceManager.GetString("S_ShowDrawingStatus", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 在闪抽窗口显示“正在抽取”,关闭后抽取期间画面保持上一轮内容,结果落定才刷新. - /// - public static string S_ShowDrawingStatus_D { - get { - return ResourceManager.GetString("S_ShowDrawingStatus_D", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 显示格式. - /// - public static string S_DisplayFormat { - get { - return ResourceManager.GetString("S_DisplayFormat", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 控制结果中显示姓名、编号或两者. - /// - public static string S_DisplayFormat_D { - get { - return ResourceManager.GetString("S_DisplayFormat_D", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 显示样式. - /// - public static string S_DisplayStyle { - get { - return ResourceManager.GetString("S_DisplayStyle", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 控制抽取结果的整体样式. - /// - public static string S_DisplayStyle_D { - get { - return ResourceManager.GetString("S_DisplayStyle_D", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 抽取模式. - /// - public static string S_DrawMode { - get { - return ResourceManager.GetString("S_DrawMode", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 控制重复抽取记录的处理方式. - /// - public static string S_DrawMode_D { - get { - return ResourceManager.GetString("S_DrawMode_D", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 抽取方式. - /// - public static string S_DrawType { - get { - return ResourceManager.GetString("S_DrawType", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 设置使用随机抽取或公平抽取. - /// - public static string S_DrawType_D { - get { - return ResourceManager.GetString("S_DrawType_D", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 固定颜色. - /// - public static string S_FixedColor { - get { - return ResourceManager.GetString("S_FixedColor", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 颜色主题为固定颜色时使用. - /// - public static string S_FixedColor_D { - get { - return ResourceManager.GetString("S_FixedColor_D", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 字体大小. - /// - public static string S_FontSize { - get { - return ResourceManager.GetString("S_FontSize", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 抽取结果文字大小. - /// - public static string S_FontSize_D { - get { - return ResourceManager.GetString("S_FontSize_D", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 字体来源. - /// - public static string S_FontSource { - get { - return ResourceManager.GetString("S_FontSource", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 跟随全局字体或为抽取结果单独指定字体. - /// - public static string S_FontSource_D { - get { - return ResourceManager.GetString("S_FontSource_D", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 半重复阈值. - /// - public static string S_HalfRepeat { - get { - return ResourceManager.GetString("S_HalfRepeat", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 抽中次数达到该值后不会再次进入候选池. - /// - public static string S_HalfRepeat_D { - get { - return ResourceManager.GetString("S_HalfRepeat_D", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 抽奖方式. - /// - public static string S_LotteryDrawType { - get { - return ResourceManager.GetString("S_LotteryDrawType", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 设置按奖盘或按剩余数量抽奖. - /// - public static string S_LotteryDrawType_D { - get { - return ResourceManager.GetString("S_LotteryDrawType_D", resourceCulture); - } - } - - public static string S_LotteryAlgorithm => ResourceManager.GetString("S_LotteryAlgorithm", resourceCulture); - public static string S_LotteryAlgorithm_D => ResourceManager.GetString("S_LotteryAlgorithm_D", resourceCulture); - public static string S_RollCallAlgorithm => ResourceManager.GetString("S_RollCallAlgorithm", resourceCulture); - public static string S_RollCallAlgorithm_D => ResourceManager.GetString("S_RollCallAlgorithm_D", resourceCulture); - public static string S_QuickDrawAlgorithm => ResourceManager.GetString("S_QuickDrawAlgorithm", resourceCulture); - public static string S_QuickDrawAlgorithm_D => ResourceManager.GetString("S_QuickDrawAlgorithm_D", resourceCulture); - public static string O_AlgorithmFair => ResourceManager.GetString("O_AlgorithmFair", resourceCulture); - public static string O_AlgorithmRandom => ResourceManager.GetString("O_AlgorithmRandom", resourceCulture); - public static string O_AlgorithmInventory => ResourceManager.GetString("O_AlgorithmInventory", resourceCulture); - public static string O_AlgorithmWeighted => ResourceManager.GetString("O_AlgorithmWeighted", resourceCulture); - - /// - /// Looks up a localized string similar to 显示奖品图片. - /// - public static string S_LotteryImage { - get { - return ResourceManager.GetString("S_LotteryImage", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 在抽奖结果中显示奖品图片。. - /// - public static string S_LotteryImage_D { - get { - return ResourceManager.GetString("S_LotteryImage_D", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 奖品图片位置. - /// - public static string S_LotteryImagePosition { - get { - return ResourceManager.GetString("S_LotteryImagePosition", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 奖品图片相对文字的位置。. - /// - public static string S_LotteryImagePosition_D { - get { - return ResourceManager.GetString("S_LotteryImagePosition_D", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 奖品图片大小. - /// - public static string S_LotteryImageSize { - get { - return ResourceManager.GetString("S_LotteryImageSize", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 抽奖结果中奖品图片的显示边长,单位为像素. - /// - public static string S_LotteryImageSize_D { - get { - return ResourceManager.GetString("S_LotteryImageSize_D", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 批量设置头像. - /// - public static string C_BatchAvatar { - get { - return ResourceManager.GetString("C_BatchAvatar", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 选择目录. - /// - public static string C_BatchAvatarChooseDirectory { - get { - return ResourceManager.GetString("C_BatchAvatarChooseDirectory", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 重新选择外部文件. - /// - public static string C_BatchAvatarChooseFile { - get { - return ResourceManager.GetString("C_BatchAvatarChooseFile", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 图片只从所选目录的第一层查找. - /// - public static string C_BatchAvatarDirectoryHint { - get { - return ResourceManager.GetString("C_BatchAvatarDirectoryHint", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 头像文件. - /// - public static string C_BatchAvatarFile { - get { - return ResourceManager.GetString("C_BatchAvatarFile", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 根据记录的名称或编号,从所选目录的第一层图片中批量匹配并设置头像. - /// - public static string C_BatchAvatarHint { - get { - return ResourceManager.GetString("C_BatchAvatarHint", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 自动匹配 {0} 条记录. - /// - public static string C_BatchAvatarMatchSummary { - get { - return ResourceManager.GetString("C_BatchAvatarMatchSummary", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 未选择目录. - /// - public static string C_BatchAvatarNoDirectorySelected { - get { - return ResourceManager.GetString("C_BatchAvatarNoDirectorySelected", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 抽奖名单. - /// - public static string C_BatchAvatarPrize { - get { - return ResourceManager.GetString("C_BatchAvatarPrize", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 记录. - /// - public static string C_BatchAvatarRecord { - get { - return ResourceManager.GetString("C_BatchAvatarRecord", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 点名名单. - /// - public static string C_BatchAvatarRoster { - get { - return ResourceManager.GetString("C_BatchAvatarRoster", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 指定点名名单. - /// - public static string C_BatchAvatarTargetRoster { - get { - return ResourceManager.GetString("C_BatchAvatarTargetRoster", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 指定抽奖名单. - /// - public static string C_BatchAvatarTargetPrize { - get { - return ResourceManager.GetString("C_BatchAvatarTargetPrize", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 设置. - /// - public static string C_BatchAvatarSet { - get { - return ResourceManager.GetString("C_BatchAvatarSet", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 取消. - /// - public static string C_Cancel { - get { - return ResourceManager.GetString("C_Cancel", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 确定. - /// - public static string C_Confirm { - get { - return ResourceManager.GetString("C_Confirm", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 设置点名名单头像. - /// - public static string C_SetAvatarViaRoster { - get { - return ResourceManager.GetString("C_SetAvatarViaRoster", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 前往点名名单页面,用成员附加设置「展示图片」设置头像. - /// - public static string C_SetAvatarViaRoster_D { - get { - return ResourceManager.GetString("C_SetAvatarViaRoster_D", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 设置抽奖名单头像. - /// - public static string C_SetAvatarViaPrize { - get { - return ResourceManager.GetString("C_SetAvatarViaPrize", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 前往抽奖名单页面,用奖品附加设置「展示图片」设置奖品图片. - /// - public static string C_SetAvatarViaPrize_D { - get { - return ResourceManager.GetString("C_SetAvatarViaPrize_D", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 已为 {0} 条记录设置头像. - /// - public static string M_BatchAvatarApplied { - get { - return ResourceManager.GetString("M_BatchAvatarApplied", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 找不到头像文件:{0}. - /// - public static string M_BatchAvatarFileNotFound { - get { - return ResourceManager.GetString("M_BatchAvatarFileNotFound", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 请先选择包含图片的目录. - /// - public static string M_BatchAvatarNoDirectory { - get { - return ResourceManager.GetString("M_BatchAvatarNoDirectory", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 抽奖过程显示. - /// - public static string S_LotteryShowRandom { - get { - return ResourceManager.GetString("S_LotteryShowRandom", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 抽奖过程中候选结果的展示格式. - /// - public static string S_LotteryShowRandom_D { - get { - return ResourceManager.GetString("S_LotteryShowRandom_D", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 自定义显示格式. - /// - public static string S_LotteryShowRandomFormat { - get { - return ResourceManager.GetString("S_LotteryShowRandomFormat", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 设置抽奖过程的自定义展示格式. - /// - public static string S_LotteryShowRandomFormat_D { - get { - return ResourceManager.GetString("S_LotteryShowRandomFormat_D", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 插入格式变量. - /// - public static string C_LotteryShowRandomFormatTokens { - get { - return ResourceManager.GetString("C_LotteryShowRandomFormatTokens", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 支持使用以下格式化变量,点按变量即可插入:. - /// - public static string C_LotteryShowRandomFormatIntro { - get { - return ResourceManager.GetString("C_LotteryShowRandomFormatIntro", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 序号. - /// - public static string C_LotteryShowRandomFormatId { - get { - return ResourceManager.GetString("C_LotteryShowRandomFormatId", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 奖项. - /// - public static string C_LotteryShowRandomFormatPrize { - get { - return ResourceManager.GetString("C_LotteryShowRandomFormatPrize", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 奖项 ID. - /// - public static string C_LotteryShowRandomFormatPrizeId { - get { - return ResourceManager.GetString("C_LotteryShowRandomFormatPrizeId", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 奖项名称. - /// - public static string C_LotteryShowRandomFormatPrizeName { - get { - return ResourceManager.GetString("C_LotteryShowRandomFormatPrizeName", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 成员. - /// - public static string C_LotteryShowRandomFormatMember { - get { - return ResourceManager.GetString("C_LotteryShowRandomFormatMember", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 成员 ID. - /// - public static string C_LotteryShowRandomFormatMemberId { - get { - return ResourceManager.GetString("C_LotteryShowRandomFormatMemberId", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 成员名字. - /// - public static string C_LotteryShowRandomFormatMemberName { - get { - return ResourceManager.GetString("C_LotteryShowRandomFormatMemberName", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 成员分组. - /// - public static string C_LotteryShowRandomFormatGroup { - get { - return ResourceManager.GetString("C_LotteryShowRandomFormatGroup", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 格式. - /// - public static string C_LotteryShowRandomFormatFormat { - get { - return ResourceManager.GetString("C_LotteryShowRandomFormatFormat", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 换行. - /// - public static string C_LotteryShowRandomFormatLineBreak { - get { - return ResourceManager.GetString("C_LotteryShowRandomFormatLineBreak", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 除换行符以外,其他分隔符可直接输入. - /// - public static string C_LotteryShowRandomFormatDirectSeparators { - get { - return ResourceManager.GetString("C_LotteryShowRandomFormatDirectSeparators", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 音乐淡入淡出. - /// - public static string S_MusicFadeInOut { - get { - return ResourceManager.GetString("S_MusicFadeInOut", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 依次设置动画音乐淡入、动画音乐淡出、结果音乐淡入和结果音乐淡出时间(毫秒)。. - /// - public static string S_MusicFadeInOut_D { - get { - return ResourceManager.GetString("S_MusicFadeInOut_D", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 音乐音量. - /// - public static string S_MusicVolume { - get { - return ResourceManager.GetString("S_MusicVolume", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 依次设置动画音乐和结果音乐的音量。. - /// - public static string S_MusicVolume_D { - get { - return ResourceManager.GetString("S_MusicVolume_D", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 提示语字体大小. - /// - public static string S_ReminderFontSize { - get { - return ResourceManager.GetString("S_ReminderFontSize", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 提示语文字大小. - /// - public static string S_ReminderFontSize_D { - get { - return ResourceManager.GetString("S_ReminderFontSize_D", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 提示语. - /// - public static string S_ReminderText { - get { - return ResourceManager.GetString("S_ReminderText", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 抽取页结果区域旁显示的提示文字. - /// - public static string S_ReminderText_D { - get { - return ResourceManager.GetString("S_ReminderText_D", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 提示语颜色. - /// - public static string S_ReminderTextColor { - get { - return ResourceManager.GetString("S_ReminderTextColor", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 提示语文字颜色. - /// - public static string S_ReminderTextColor_D { - get { - return ResourceManager.GetString("S_ReminderTextColor_D", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 提示语透明度. - /// - public static string S_ReminderTextOpacity { - get { - return ResourceManager.GetString("S_ReminderTextOpacity", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 提示语文字透明度(0-100). - /// - public static string S_ReminderTextOpacity_D { - get { - return ResourceManager.GetString("S_ReminderTextOpacity_D", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 结果音乐. - /// - public static string S_ResultMusic { - get { - return ResourceManager.GetString("S_ResultMusic", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 选择抽取结果出现时使用的音乐。. - /// - public static string S_ResultMusic_D { - get { - return ResourceManager.GetString("S_ResultMusic_D", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 结果音乐淡入和淡出. - /// - public static string S_ResultMusicFade { - get { - return ResourceManager.GetString("S_ResultMusicFade", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 上方滑块控制淡入,下方滑块控制淡出,单位为毫秒。. - /// - public static string S_ResultMusicFade_D { - get { - return ResourceManager.GetString("S_ResultMusicFade_D", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 结果音乐音量. - /// - public static string S_ResultMusicVolume { - get { - return ResourceManager.GetString("S_ResultMusicVolume", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 设置抽取结果音乐的音量。. - /// - public static string S_ResultMusicVolume_D { - get { - return ResourceManager.GetString("S_ResultMusicVolume_D", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 显示标签. - /// - public static string S_ShowTags { - get { - return ResourceManager.GetString("S_ShowTags", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 抽取结果中展示学生或奖品标签. - /// - public static string S_ShowTags_D { - get { - return ResourceManager.GetString("S_ShowTags_D", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 权重透明化. - /// - public static string S_ShowWeightTransparency { - get { - return ResourceManager.GetString("S_ShowWeightTransparency", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 在结果展示中显示权重透明信息. - /// - public static string S_ShowWeightTransparency_D { - get { - return ResourceManager.GetString("S_ShowWeightTransparency_D", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 显示头像. - /// - public static string S_StudentImage { - get { - return ResourceManager.GetString("S_StudentImage", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 在抽取结果中显示学生头像. - /// - public static string S_StudentImage_D { - get { - return ResourceManager.GetString("S_StudentImage_D", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 头像位置. - /// - public static string S_StudentImagePosition { - get { - return ResourceManager.GetString("S_StudentImagePosition", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 学生头像相对文字的位置. - /// - public static string S_StudentImagePosition_D { - get { - return ResourceManager.GetString("S_StudentImagePosition_D", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 头像大小. - /// - public static string S_StudentImageSize { - get { - return ResourceManager.GetString("S_StudentImageSize", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 抽取结果中头像的显示边长,单位为像素. - /// - public static string S_StudentImageSize_D { - get { - return ResourceManager.GetString("S_StudentImageSize_D", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 启用语音播报. - /// - public static string S_VoiceAnnouncementEnabled { - get { - return ResourceManager.GetString("S_VoiceAnnouncementEnabled", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 抽取完成后播报结果;全局语音播报开关关闭时,此设置不会生效。. - /// - public static string S_VoiceAnnouncementEnabled_D { - get { - return ResourceManager.GetString("S_VoiceAnnouncementEnabled_D", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 动画设置. - /// - public static string Section_Animation { - get { - return ResourceManager.GetString("Section_Animation", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 颜色设置. - /// - public static string Section_Color { - get { - return ResourceManager.GetString("Section_Color", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 显示设置. - /// - public static string Section_Display { - get { - return ResourceManager.GetString("Section_Display", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 抽取设置. - /// - public static string Section_Draw { - get { - return ResourceManager.GetString("Section_Draw", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 奖品图片设置. - /// - public static string Section_LotteryImage { - get { - return ResourceManager.GetString("Section_LotteryImage", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 音乐设置. - /// - public static string Section_Music { - get { - return ResourceManager.GetString("Section_Music", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 可覆盖的设置. - /// - public static string Section_Overridable { - get { - return ResourceManager.GetString("Section_Overridable", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 提示语设置. - /// - public static string Section_Reminder { - get { - return ResourceManager.GetString("Section_Reminder", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 学生头像设置. - /// - public static string Section_StudentImage { - get { - return ResourceManager.GetString("Section_StudentImage", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 语音播报. - /// - public static string Section_VoiceAnnouncement { - get { - return ResourceManager.GetString("Section_VoiceAnnouncement", resourceCulture); - } - } - /// - /// Looks up a localized string similar to 记录组. - /// - public static string S_RollCallHistoryGroup { - get { - return ResourceManager.GetString("S_RollCallHistoryGroup", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 选中后点名页默认按该组的历史计算权重,本次记录也只写进该组;选「默认记录组」表示只算未分组的记录. - /// - public static string S_RollCallHistoryGroup_D { - get { - return ResourceManager.GetString("S_RollCallHistoryGroup_D", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 记录组. - /// - public static string S_LotteryHistoryGroup { - get { - return ResourceManager.GetString("S_LotteryHistoryGroup", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 选中后抽奖页默认按该组的历史计算权重,本次记录也只写进该组;选「默认记录组」表示只算未分组的记录. - /// - public static string S_LotteryHistoryGroup_D { - get { - return ResourceManager.GetString("S_LotteryHistoryGroup_D", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 记录组. - /// - public static string S_QuickDrawHistoryGroup { - get { - return ResourceManager.GetString("S_QuickDrawHistoryGroup", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 选中后闪抽只按该组的历史计算权重,本次记录也只写进该组;选「默认记录组」表示只算未分组的记录. - /// - public static string S_QuickDrawHistoryGroup_D { - get { - return ResourceManager.GetString("S_QuickDrawHistoryGroup_D", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 默认记录组. - /// - public static string O_HistoryGroupDefault { - get { - return ResourceManager.GetString("O_HistoryGroupDefault", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 历史记录组功能未启用,可在「历史记录管理」里打开. - /// - public static string S_HistoryGroup_Disabled { - get { - return ResourceManager.GetString("S_HistoryGroup_Disabled", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 随机数抽取. - /// - public static string Page_RandomNumber { - get { - return ResourceManager.GetString("Page_RandomNumber", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 默认范围与个数. - /// - public static string Section_RandomNumber_Defaults { - get { - return ResourceManager.GetString("Section_RandomNumber_Defaults", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 点名默认范围. - /// - public static string S_RandomNumber_RollCallRange { - get { - return ResourceManager.GetString("S_RandomNumber_RollCallRange", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 打开点名页时默认使用的数字范围,起点不小于 0,跨度最多 200. - /// - public static string S_RandomNumber_RollCallRange_D { - get { - return ResourceManager.GetString("S_RandomNumber_RollCallRange_D", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 点名默认个数. - /// - public static string S_RandomNumber_RollCallCount { - get { - return ResourceManager.GetString("S_RandomNumber_RollCallCount", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 打开点名页时默认抽取的数字个数. - /// - public static string S_RandomNumber_RollCallCount_D { - get { - return ResourceManager.GetString("S_RandomNumber_RollCallCount_D", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 抽奖默认范围. - /// - public static string S_RandomNumber_LotteryRange { - get { - return ResourceManager.GetString("S_RandomNumber_LotteryRange", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 打开抽奖页时默认使用的数字范围,起点不小于 0,跨度最多 200. - /// - public static string S_RandomNumber_LotteryRange_D { - get { - return ResourceManager.GetString("S_RandomNumber_LotteryRange_D", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 抽奖默认个数. - /// - public static string S_RandomNumber_LotteryCount { - get { - return ResourceManager.GetString("S_RandomNumber_LotteryCount", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 打开抽奖页时默认抽取的数字个数. - /// - public static string S_RandomNumber_LotteryCount_D { - get { - return ResourceManager.GetString("S_RandomNumber_LotteryCount_D", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 至. - /// - public static string C_RandomNumber_To { - get { - return ResourceManager.GetString("C_RandomNumber_To", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 重置行为. - /// - public static string S_RandomNumber_ResetBehavior { - get { - return ResourceManager.GetString("S_RandomNumber_ResetBehavior", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 重置随机数抽取时如何处理统计. - /// - public static string S_RandomNumber_ResetBehavior_D { - get { - return ResourceManager.GetString("S_RandomNumber_ResetBehavior_D", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 只清临时剩余. - /// - public static string O_RandomNumber_ResetTemporaryOnly { - get { - return ResourceManager.GetString("O_RandomNumber_ResetTemporaryOnly", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 同时清除统计. - /// - public static string O_RandomNumber_ResetTemporaryAndStatistics { - get { - return ResourceManager.GetString("O_RandomNumber_ResetTemporaryAndStatistics", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 抽取规则. - /// - public static string Section_RandomNumber_Rules { - get { - return ResourceManager.GetString("Section_RandomNumber_Rules", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 每个数字等概率抽取,重复规则沿用点名或抽奖页当前设置,范围跨度上限 200,名单历史不受随机数重置影响. - /// - public static string M_RandomNumber_Rules { - get { - return ResourceManager.GetString("M_RandomNumber_Rules", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 随机数统计. - /// - public static string Section_RandomNumber_Statistics { - get { - return ResourceManager.GetString("Section_RandomNumber_Statistics", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 累计统计. - /// - public static string S_RandomNumber_Statistics { - get { - return ResourceManager.GetString("S_RandomNumber_Statistics", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 只统计提交成功的数字抽取,最多保留最近 100 次记录. - /// - public static string S_RandomNumber_Statistics_D { - get { - return ResourceManager.GetString("S_RandomNumber_Statistics_D", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 累计轮次. - /// - public static string M_RandomNumber_TotalRounds { - get { - return ResourceManager.GetString("M_RandomNumber_TotalRounds", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 累计数字. - /// - public static string M_RandomNumber_TotalDrawnCount { - get { - return ResourceManager.GetString("M_RandomNumber_TotalDrawnCount", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 清除统计. - /// - public static string C_RandomNumber_ClearStatistics { - get { - return ResourceManager.GetString("C_RandomNumber_ClearStatistics", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to 暂无统计. - /// - public static string M_RandomNumber_NoStatistics { - get { - return ResourceManager.GetString("M_RandomNumber_NoStatistics", resourceCulture); - } - } - - } -} +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace SecRandom.Langs.SettingsPages.Picking { + using System; + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + public class Resources { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + public static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("SecRandom.Langs.SettingsPages.Picking.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + public static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + + /// + /// Looks up a localized string similar to 启用覆盖. + /// + public static string C_EnableOverride { + get { + return ResourceManager.GetString("C_EnableOverride", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 淡入. + /// + public static string C_FadeIn { + get { + return ResourceManager.GetString("C_FadeIn", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 淡出. + /// + public static string C_FadeOut { + get { + return ResourceManager.GetString("C_FadeOut", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 直接轮换. + /// + public static string O_AnimationDirectRotate { + get { + return ResourceManager.GetString("O_AnimationDirectRotate", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 淡入上浮. + /// + public static string O_AnimationFadeFloat { + get { + return ResourceManager.GetString("O_AnimationFadeFloat", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 左右晃动. + /// + public static string O_AnimationHorizontalShake { + get { + return ResourceManager.GetString("O_AnimationHorizontalShake", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 自动播放. + /// + public static string O_AutoPlay { + get { + return ResourceManager.GetString("O_AutoPlay", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 编号和姓名. + /// + public static string O_Both { + get { + return ResourceManager.GetString("O_Both", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 下方. + /// + public static string O_Bottom { + get { + return ResourceManager.GetString("O_Bottom", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 卡片. + /// + public static string O_Card { + get { + return ResourceManager.GetString("O_Card", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 手动清除. + /// + public static string O_Cleared { + get { + return ResourceManager.GetString("O_Cleared", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 按剩余数量. + /// + public static string O_Count { + get { + return ResourceManager.GetString("O_Count", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 自定义. + /// + public static string O_Custom { + get { + return ResourceManager.GetString("O_Custom", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 默认. + /// + public static string O_Default { + get { + return ResourceManager.GetString("O_Default", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 公平抽取. + /// + public static string O_Fair { + get { + return ResourceManager.GetString("O_Fair", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 固定颜色. + /// + public static string O_FixedColor { + get { + return ResourceManager.GetString("O_FixedColor", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 跟随全局. + /// + public static string O_FollowGlobal { + get { + return ResourceManager.GetString("O_FollowGlobal", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 半重复. + /// + public static string O_HalfRepeat { + get { + return ResourceManager.GetString("O_HalfRepeat", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 仅编号. + /// + public static string O_Id { + get { + return ResourceManager.GetString("O_Id", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 左侧. + /// + public static string O_Left { + get { + return ResourceManager.GetString("O_Left", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 手动停止. + /// + public static string O_ManualStop { + get { + return ResourceManager.GetString("O_ManualStop", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 外部文件:{0}. + /// + public static string O_MusicExternal { + get { + return ResourceManager.GetString("O_MusicExternal", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 不可用:{0}. + /// + public static string O_MusicUnavailable { + get { + return ResourceManager.GetString("O_MusicUnavailable", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 仅姓名. + /// + public static string O_Name { + get { + return ResourceManager.GetString("O_Name", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 无动画. + /// + public static string O_NoAnimation { + get { + return ResourceManager.GetString("O_NoAnimation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 无. + /// + public static string O_NoColor { + get { + return ResourceManager.GetString("O_NoColor", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 不开启音乐. + /// + public static string O_NoMusic { + get { + return ResourceManager.GetString("O_NoMusic", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 不重复. + /// + public static string O_NoRepeat { + get { + return ResourceManager.GetString("O_NoRepeat", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 按奖盘. + /// + public static string O_Pan { + get { + return ResourceManager.GetString("O_Pan", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 奖品/小组. + /// + public static string O_PrizeBreakGroup { + get { + return ResourceManager.GetString("O_PrizeBreakGroup", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 奖品/小组/姓名. + /// + public static string O_PrizeBreakGroupBreakName { + get { + return ResourceManager.GetString("O_PrizeBreakGroupBreakName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 奖品/小组-姓名. + /// + public static string O_PrizeBreakGroupHyphenName { + get { + return ResourceManager.GetString("O_PrizeBreakGroupHyphenName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 奖品/姓名. + /// + public static string O_PrizeBreakName { + get { + return ResourceManager.GetString("O_PrizeBreakName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 奖品-小组. + /// + public static string O_PrizeHyphenGroup { + get { + return ResourceManager.GetString("O_PrizeHyphenGroup", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 奖品-小组-姓名. + /// + public static string O_PrizeHyphenGroupHyphenName { + get { + return ResourceManager.GetString("O_PrizeHyphenGroupHyphenName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 奖品-姓名. + /// + public static string O_PrizeHyphenName { + get { + return ResourceManager.GetString("O_PrizeHyphenName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 序号 奖品/分组-名称. + /// + public static string O_PrizeIdPrizeBreakGroupHyphenMember { + get { + return ResourceManager.GetString("O_PrizeIdPrizeBreakGroupHyphenMember", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 随机抽取. + /// + public static string O_Random { + get { + return ResourceManager.GetString("O_Random", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 随机. + /// + public static string O_RandomColor { + get { + return ResourceManager.GetString("O_RandomColor", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 随机播放. + /// + public static string O_RandomMusic { + get { + return ResourceManager.GetString("O_RandomMusic", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 允许重复. + /// + public static string O_Repeat { + get { + return ResourceManager.GetString("O_Repeat", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 重启后清除. + /// + public static string O_Restarted { + get { + return ResourceManager.GetString("O_Restarted", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 右侧. + /// + public static string O_Right { + get { + return ResourceManager.GetString("O_Right", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 上方. + /// + public static string O_Top { + get { + return ResourceManager.GetString("O_Top", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 默认抽取设置. + /// + public static string Page_Default { + get { + return ResourceManager.GetString("Page_Default", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 抽奖抽取设置. + /// + public static string Page_Lottery { + get { + return ResourceManager.GetString("Page_Lottery", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 闪抽抽取设置. + /// + public static string Page_QuickDraw { + get { + return ResourceManager.GetString("Page_QuickDraw", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 点名抽取设置. + /// + public static string Page_RollCall { + get { + return ResourceManager.GetString("Page_RollCall", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 动画模式. + /// + public static string S_Animation { + get { + return ResourceManager.GetString("S_Animation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 设置抽取动画播放方式. + /// + public static string S_Animation_D { + get { + return ResourceManager.GetString("S_Animation_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 动画间隔. + /// + public static string S_AnimationInterval { + get { + return ResourceManager.GetString("S_AnimationInterval", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 抽取动画每次切换的间隔(毫秒). + /// + public static string S_AnimationInterval_D { + get { + return ResourceManager.GetString("S_AnimationInterval_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 动画音乐. + /// + public static string S_AnimationMusic { + get { + return ResourceManager.GetString("S_AnimationMusic", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 选择抽取动画播放时使用的音乐。. + /// + public static string S_AnimationMusic_D { + get { + return ResourceManager.GetString("S_AnimationMusic_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 循环播放动画音乐. + /// + public static string S_AnimationMusicLoop { + get { + return ResourceManager.GetString("S_AnimationMusicLoop", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 动画持续期间重复播放动画音乐。. + /// + public static string S_AnimationMusicLoop_D { + get { + return ResourceManager.GetString("S_AnimationMusicLoop_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 动画音乐淡入和淡出. + /// + public static string S_AnimationMusicFade { + get { + return ResourceManager.GetString("S_AnimationMusicFade", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 上方滑块控制淡入,下方滑块控制淡出,单位为毫秒。. + /// + public static string S_AnimationMusicFade_D { + get { + return ResourceManager.GetString("S_AnimationMusicFade_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 动画音乐音量. + /// + public static string S_AnimationMusicVolume { + get { + return ResourceManager.GetString("S_AnimationMusicVolume", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 设置抽取动画音乐的音量。. + /// + public static string S_AnimationMusicVolume_D { + get { + return ResourceManager.GetString("S_AnimationMusicVolume_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 动画样式. + /// + public static string S_AnimationStyle { + get { + return ResourceManager.GetString("S_AnimationStyle", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 设置抽取过程和最终定格时使用的统一动画效果. + /// + public static string S_AnimationStyle_D { + get { + return ResourceManager.GetString("S_AnimationStyle_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 自动播放次数. + /// + public static string S_AutoplayCount { + get { + return ResourceManager.GetString("S_AutoplayCount", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 自动播放模式下滚动候选结果的次数. + /// + public static string S_AutoplayCount_D { + get { + return ResourceManager.GetString("S_AutoplayCount_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 清除记录. + /// + public static string S_ClearRecord { + get { + return ResourceManager.GetString("S_ClearRecord", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 控制抽取记录何时清除. + /// + public static string S_ClearRecord_D { + get { + return ResourceManager.GetString("S_ClearRecord_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 颜色主题. + /// + public static string S_ColorTheme { + get { + return ResourceManager.GetString("S_ColorTheme", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 设置抽取动画和结果颜色来源. + /// + public static string S_ColorTheme_D { + get { + return ResourceManager.GetString("S_ColorTheme_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 自定义字体. + /// + public static string S_CustomFont { + get { + return ResourceManager.GetString("S_CustomFont", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 字体族名称,留空时使用默认字体. + /// + public static string S_CustomFont_D { + get { + return ResourceManager.GetString("S_CustomFont_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 默认抽取名单. + /// + public static string S_DefaultClass { + get { + return ResourceManager.GetString("S_DefaultClass", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 打开页面或执行闪抽时默认使用的名单. + /// + public static string S_DefaultClass_D { + get { + return ResourceManager.GetString("S_DefaultClass_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 默认抽奖名单. + /// + public static string S_DefaultPool { + get { + return ResourceManager.GetString("S_DefaultPool", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 打开抽奖页时默认使用的奖池. + /// + public static string S_DefaultPool_D { + get { + return ResourceManager.GetString("S_DefaultPool_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 不使用名单. + /// + public static string O_NoList { + get { + return ResourceManager.GetString("O_NoList", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 点击后禁用时间. + /// + public static string S_DisableAfterClick { + get { + return ResourceManager.GetString("S_DisableAfterClick", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 点击一次闪抽后禁用按钮的秒数. + /// + public static string S_DisableAfterClick_D { + get { + return ResourceManager.GetString("S_DisableAfterClick_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 显示抽取中状态. + /// + public static string S_ShowDrawingStatus { + get { + return ResourceManager.GetString("S_ShowDrawingStatus", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 在闪抽窗口显示“正在抽取”,关闭后抽取期间画面保持上一轮内容,结果落定才刷新. + /// + public static string S_ShowDrawingStatus_D { + get { + return ResourceManager.GetString("S_ShowDrawingStatus_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 显示格式. + /// + public static string S_DisplayFormat { + get { + return ResourceManager.GetString("S_DisplayFormat", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 控制结果中显示姓名、编号或两者. + /// + public static string S_DisplayFormat_D { + get { + return ResourceManager.GetString("S_DisplayFormat_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 显示样式. + /// + public static string S_DisplayStyle { + get { + return ResourceManager.GetString("S_DisplayStyle", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 控制抽取结果的整体样式. + /// + public static string S_DisplayStyle_D { + get { + return ResourceManager.GetString("S_DisplayStyle_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 抽取模式. + /// + public static string S_DrawMode { + get { + return ResourceManager.GetString("S_DrawMode", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 控制重复抽取记录的处理方式. + /// + public static string S_DrawMode_D { + get { + return ResourceManager.GetString("S_DrawMode_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 抽取方式. + /// + public static string S_DrawType { + get { + return ResourceManager.GetString("S_DrawType", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 设置使用随机抽取或公平抽取. + /// + public static string S_DrawType_D { + get { + return ResourceManager.GetString("S_DrawType_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 固定颜色. + /// + public static string S_FixedColor { + get { + return ResourceManager.GetString("S_FixedColor", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 颜色主题为固定颜色时使用. + /// + public static string S_FixedColor_D { + get { + return ResourceManager.GetString("S_FixedColor_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 字体大小. + /// + public static string S_FontSize { + get { + return ResourceManager.GetString("S_FontSize", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 抽取结果文字大小. + /// + public static string S_FontSize_D { + get { + return ResourceManager.GetString("S_FontSize_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 字体来源. + /// + public static string S_FontSource { + get { + return ResourceManager.GetString("S_FontSource", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 跟随全局字体或为抽取结果单独指定字体. + /// + public static string S_FontSource_D { + get { + return ResourceManager.GetString("S_FontSource_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 半重复阈值. + /// + public static string S_HalfRepeat { + get { + return ResourceManager.GetString("S_HalfRepeat", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 抽中次数达到该值后不会再次进入候选池. + /// + public static string S_HalfRepeat_D { + get { + return ResourceManager.GetString("S_HalfRepeat_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 抽奖方式. + /// + public static string S_LotteryDrawType { + get { + return ResourceManager.GetString("S_LotteryDrawType", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 设置按奖盘或按剩余数量抽奖. + /// + public static string S_LotteryDrawType_D { + get { + return ResourceManager.GetString("S_LotteryDrawType_D", resourceCulture); + } + } + + public static string S_LotteryAlgorithm => ResourceManager.GetString("S_LotteryAlgorithm", resourceCulture); + public static string S_LotteryAlgorithm_D => ResourceManager.GetString("S_LotteryAlgorithm_D", resourceCulture); + public static string S_RollCallAlgorithm => ResourceManager.GetString("S_RollCallAlgorithm", resourceCulture); + public static string S_RollCallAlgorithm_D => ResourceManager.GetString("S_RollCallAlgorithm_D", resourceCulture); + public static string S_QuickDrawAlgorithm => ResourceManager.GetString("S_QuickDrawAlgorithm", resourceCulture); + public static string S_QuickDrawAlgorithm_D => ResourceManager.GetString("S_QuickDrawAlgorithm_D", resourceCulture); + public static string O_AlgorithmFair => ResourceManager.GetString("O_AlgorithmFair", resourceCulture); + public static string O_AlgorithmRandom => ResourceManager.GetString("O_AlgorithmRandom", resourceCulture); + public static string O_AlgorithmInventory => ResourceManager.GetString("O_AlgorithmInventory", resourceCulture); + public static string O_AlgorithmWeighted => ResourceManager.GetString("O_AlgorithmWeighted", resourceCulture); + public static string S_FairDrawMode => ResourceManager.GetString("S_FairDrawMode", resourceCulture); + public static string S_FairDrawMode_D => ResourceManager.GetString("S_FairDrawMode_D", resourceCulture); + public static string O_FairDrawModeUniform => ResourceManager.GetString("O_FairDrawModeUniform", resourceCulture); + public static string O_FairDrawModeRandom => ResourceManager.GetString("O_FairDrawModeRandom", resourceCulture); + + /// + /// Looks up a localized string similar to 显示奖品图片. + /// + public static string S_LotteryImage { + get { + return ResourceManager.GetString("S_LotteryImage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 在抽奖结果中显示奖品图片。. + /// + public static string S_LotteryImage_D { + get { + return ResourceManager.GetString("S_LotteryImage_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 奖品图片位置. + /// + public static string S_LotteryImagePosition { + get { + return ResourceManager.GetString("S_LotteryImagePosition", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 奖品图片相对文字的位置。. + /// + public static string S_LotteryImagePosition_D { + get { + return ResourceManager.GetString("S_LotteryImagePosition_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 奖品图片大小. + /// + public static string S_LotteryImageSize { + get { + return ResourceManager.GetString("S_LotteryImageSize", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 抽奖结果中奖品图片的显示边长,单位为像素. + /// + public static string S_LotteryImageSize_D { + get { + return ResourceManager.GetString("S_LotteryImageSize_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 批量设置头像. + /// + public static string C_BatchAvatar { + get { + return ResourceManager.GetString("C_BatchAvatar", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 选择目录. + /// + public static string C_BatchAvatarChooseDirectory { + get { + return ResourceManager.GetString("C_BatchAvatarChooseDirectory", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 重新选择外部文件. + /// + public static string C_BatchAvatarChooseFile { + get { + return ResourceManager.GetString("C_BatchAvatarChooseFile", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 图片只从所选目录的第一层查找. + /// + public static string C_BatchAvatarDirectoryHint { + get { + return ResourceManager.GetString("C_BatchAvatarDirectoryHint", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 头像文件. + /// + public static string C_BatchAvatarFile { + get { + return ResourceManager.GetString("C_BatchAvatarFile", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 根据记录的名称或编号,从所选目录的第一层图片中批量匹配并设置头像. + /// + public static string C_BatchAvatarHint { + get { + return ResourceManager.GetString("C_BatchAvatarHint", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 自动匹配 {0} 条记录. + /// + public static string C_BatchAvatarMatchSummary { + get { + return ResourceManager.GetString("C_BatchAvatarMatchSummary", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 未选择目录. + /// + public static string C_BatchAvatarNoDirectorySelected { + get { + return ResourceManager.GetString("C_BatchAvatarNoDirectorySelected", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 抽奖名单. + /// + public static string C_BatchAvatarPrize { + get { + return ResourceManager.GetString("C_BatchAvatarPrize", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 记录. + /// + public static string C_BatchAvatarRecord { + get { + return ResourceManager.GetString("C_BatchAvatarRecord", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 点名名单. + /// + public static string C_BatchAvatarRoster { + get { + return ResourceManager.GetString("C_BatchAvatarRoster", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 指定点名名单. + /// + public static string C_BatchAvatarTargetRoster { + get { + return ResourceManager.GetString("C_BatchAvatarTargetRoster", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 指定抽奖名单. + /// + public static string C_BatchAvatarTargetPrize { + get { + return ResourceManager.GetString("C_BatchAvatarTargetPrize", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 设置. + /// + public static string C_BatchAvatarSet { + get { + return ResourceManager.GetString("C_BatchAvatarSet", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 取消. + /// + public static string C_Cancel { + get { + return ResourceManager.GetString("C_Cancel", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 确定. + /// + public static string C_Confirm { + get { + return ResourceManager.GetString("C_Confirm", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 设置点名名单头像. + /// + public static string C_SetAvatarViaRoster { + get { + return ResourceManager.GetString("C_SetAvatarViaRoster", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 前往点名名单页面,用成员附加设置「展示图片」设置头像. + /// + public static string C_SetAvatarViaRoster_D { + get { + return ResourceManager.GetString("C_SetAvatarViaRoster_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 设置抽奖名单头像. + /// + public static string C_SetAvatarViaPrize { + get { + return ResourceManager.GetString("C_SetAvatarViaPrize", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 前往抽奖名单页面,用奖品附加设置「展示图片」设置奖品图片. + /// + public static string C_SetAvatarViaPrize_D { + get { + return ResourceManager.GetString("C_SetAvatarViaPrize_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 已为 {0} 条记录设置头像. + /// + public static string M_BatchAvatarApplied { + get { + return ResourceManager.GetString("M_BatchAvatarApplied", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 找不到头像文件:{0}. + /// + public static string M_BatchAvatarFileNotFound { + get { + return ResourceManager.GetString("M_BatchAvatarFileNotFound", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 请先选择包含图片的目录. + /// + public static string M_BatchAvatarNoDirectory { + get { + return ResourceManager.GetString("M_BatchAvatarNoDirectory", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 抽奖过程显示. + /// + public static string S_LotteryShowRandom { + get { + return ResourceManager.GetString("S_LotteryShowRandom", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 抽奖过程中候选结果的展示格式. + /// + public static string S_LotteryShowRandom_D { + get { + return ResourceManager.GetString("S_LotteryShowRandom_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 自定义显示格式. + /// + public static string S_LotteryShowRandomFormat { + get { + return ResourceManager.GetString("S_LotteryShowRandomFormat", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 设置抽奖过程的自定义展示格式. + /// + public static string S_LotteryShowRandomFormat_D { + get { + return ResourceManager.GetString("S_LotteryShowRandomFormat_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 插入格式变量. + /// + public static string C_LotteryShowRandomFormatTokens { + get { + return ResourceManager.GetString("C_LotteryShowRandomFormatTokens", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 支持使用以下格式化变量,点按变量即可插入:. + /// + public static string C_LotteryShowRandomFormatIntro { + get { + return ResourceManager.GetString("C_LotteryShowRandomFormatIntro", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 序号. + /// + public static string C_LotteryShowRandomFormatId { + get { + return ResourceManager.GetString("C_LotteryShowRandomFormatId", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 奖项. + /// + public static string C_LotteryShowRandomFormatPrize { + get { + return ResourceManager.GetString("C_LotteryShowRandomFormatPrize", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 奖项 ID. + /// + public static string C_LotteryShowRandomFormatPrizeId { + get { + return ResourceManager.GetString("C_LotteryShowRandomFormatPrizeId", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 奖项名称. + /// + public static string C_LotteryShowRandomFormatPrizeName { + get { + return ResourceManager.GetString("C_LotteryShowRandomFormatPrizeName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 成员. + /// + public static string C_LotteryShowRandomFormatMember { + get { + return ResourceManager.GetString("C_LotteryShowRandomFormatMember", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 成员 ID. + /// + public static string C_LotteryShowRandomFormatMemberId { + get { + return ResourceManager.GetString("C_LotteryShowRandomFormatMemberId", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 成员名字. + /// + public static string C_LotteryShowRandomFormatMemberName { + get { + return ResourceManager.GetString("C_LotteryShowRandomFormatMemberName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 成员分组. + /// + public static string C_LotteryShowRandomFormatGroup { + get { + return ResourceManager.GetString("C_LotteryShowRandomFormatGroup", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 格式. + /// + public static string C_LotteryShowRandomFormatFormat { + get { + return ResourceManager.GetString("C_LotteryShowRandomFormatFormat", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 换行. + /// + public static string C_LotteryShowRandomFormatLineBreak { + get { + return ResourceManager.GetString("C_LotteryShowRandomFormatLineBreak", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 除换行符以外,其他分隔符可直接输入. + /// + public static string C_LotteryShowRandomFormatDirectSeparators { + get { + return ResourceManager.GetString("C_LotteryShowRandomFormatDirectSeparators", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 音乐淡入淡出. + /// + public static string S_MusicFadeInOut { + get { + return ResourceManager.GetString("S_MusicFadeInOut", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 依次设置动画音乐淡入、动画音乐淡出、结果音乐淡入和结果音乐淡出时间(毫秒)。. + /// + public static string S_MusicFadeInOut_D { + get { + return ResourceManager.GetString("S_MusicFadeInOut_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 音乐音量. + /// + public static string S_MusicVolume { + get { + return ResourceManager.GetString("S_MusicVolume", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 依次设置动画音乐和结果音乐的音量。. + /// + public static string S_MusicVolume_D { + get { + return ResourceManager.GetString("S_MusicVolume_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 提示语字体大小. + /// + public static string S_ReminderFontSize { + get { + return ResourceManager.GetString("S_ReminderFontSize", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 提示语文字大小. + /// + public static string S_ReminderFontSize_D { + get { + return ResourceManager.GetString("S_ReminderFontSize_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 提示语. + /// + public static string S_ReminderText { + get { + return ResourceManager.GetString("S_ReminderText", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 抽取页结果区域旁显示的提示文字. + /// + public static string S_ReminderText_D { + get { + return ResourceManager.GetString("S_ReminderText_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 提示语颜色. + /// + public static string S_ReminderTextColor { + get { + return ResourceManager.GetString("S_ReminderTextColor", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 提示语文字颜色. + /// + public static string S_ReminderTextColor_D { + get { + return ResourceManager.GetString("S_ReminderTextColor_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 提示语透明度. + /// + public static string S_ReminderTextOpacity { + get { + return ResourceManager.GetString("S_ReminderTextOpacity", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 提示语文字透明度(0-100). + /// + public static string S_ReminderTextOpacity_D { + get { + return ResourceManager.GetString("S_ReminderTextOpacity_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 结果音乐. + /// + public static string S_ResultMusic { + get { + return ResourceManager.GetString("S_ResultMusic", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 选择抽取结果出现时使用的音乐。. + /// + public static string S_ResultMusic_D { + get { + return ResourceManager.GetString("S_ResultMusic_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 结果音乐淡入和淡出. + /// + public static string S_ResultMusicFade { + get { + return ResourceManager.GetString("S_ResultMusicFade", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 上方滑块控制淡入,下方滑块控制淡出,单位为毫秒。. + /// + public static string S_ResultMusicFade_D { + get { + return ResourceManager.GetString("S_ResultMusicFade_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 结果音乐音量. + /// + public static string S_ResultMusicVolume { + get { + return ResourceManager.GetString("S_ResultMusicVolume", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 设置抽取结果音乐的音量。. + /// + public static string S_ResultMusicVolume_D { + get { + return ResourceManager.GetString("S_ResultMusicVolume_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 显示标签. + /// + public static string S_ShowTags { + get { + return ResourceManager.GetString("S_ShowTags", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 抽取结果中展示学生或奖品标签. + /// + public static string S_ShowTags_D { + get { + return ResourceManager.GetString("S_ShowTags_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 权重透明化. + /// + public static string S_ShowWeightTransparency { + get { + return ResourceManager.GetString("S_ShowWeightTransparency", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 在结果展示中显示权重透明信息. + /// + public static string S_ShowWeightTransparency_D { + get { + return ResourceManager.GetString("S_ShowWeightTransparency_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 显示头像. + /// + public static string S_StudentImage { + get { + return ResourceManager.GetString("S_StudentImage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 在抽取结果中显示学生头像. + /// + public static string S_StudentImage_D { + get { + return ResourceManager.GetString("S_StudentImage_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 头像位置. + /// + public static string S_StudentImagePosition { + get { + return ResourceManager.GetString("S_StudentImagePosition", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 学生头像相对文字的位置. + /// + public static string S_StudentImagePosition_D { + get { + return ResourceManager.GetString("S_StudentImagePosition_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 头像大小. + /// + public static string S_StudentImageSize { + get { + return ResourceManager.GetString("S_StudentImageSize", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 抽取结果中头像的显示边长,单位为像素. + /// + public static string S_StudentImageSize_D { + get { + return ResourceManager.GetString("S_StudentImageSize_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 启用语音播报. + /// + public static string S_VoiceAnnouncementEnabled { + get { + return ResourceManager.GetString("S_VoiceAnnouncementEnabled", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 抽取完成后播报结果;全局语音播报开关关闭时,此设置不会生效。. + /// + public static string S_VoiceAnnouncementEnabled_D { + get { + return ResourceManager.GetString("S_VoiceAnnouncementEnabled_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 动画设置. + /// + public static string Section_Animation { + get { + return ResourceManager.GetString("Section_Animation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 颜色设置. + /// + public static string Section_Color { + get { + return ResourceManager.GetString("Section_Color", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 显示设置. + /// + public static string Section_Display { + get { + return ResourceManager.GetString("Section_Display", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 抽取设置. + /// + public static string Section_Draw { + get { + return ResourceManager.GetString("Section_Draw", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 奖品图片设置. + /// + public static string Section_LotteryImage { + get { + return ResourceManager.GetString("Section_LotteryImage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 音乐设置. + /// + public static string Section_Music { + get { + return ResourceManager.GetString("Section_Music", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 可覆盖的设置. + /// + public static string Section_Overridable { + get { + return ResourceManager.GetString("Section_Overridable", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 提示语设置. + /// + public static string Section_Reminder { + get { + return ResourceManager.GetString("Section_Reminder", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 学生头像设置. + /// + public static string Section_StudentImage { + get { + return ResourceManager.GetString("Section_StudentImage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 语音播报. + /// + public static string Section_VoiceAnnouncement { + get { + return ResourceManager.GetString("Section_VoiceAnnouncement", resourceCulture); + } + } + /// + /// Looks up a localized string similar to 记录组. + /// + public static string S_RollCallHistoryGroup { + get { + return ResourceManager.GetString("S_RollCallHistoryGroup", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 选中后点名页默认按该组的历史计算权重,本次记录也只写进该组;选「默认记录组」表示只算未分组的记录. + /// + public static string S_RollCallHistoryGroup_D { + get { + return ResourceManager.GetString("S_RollCallHistoryGroup_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 记录组. + /// + public static string S_LotteryHistoryGroup { + get { + return ResourceManager.GetString("S_LotteryHistoryGroup", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 选中后抽奖页默认按该组的历史计算权重,本次记录也只写进该组;选「默认记录组」表示只算未分组的记录. + /// + public static string S_LotteryHistoryGroup_D { + get { + return ResourceManager.GetString("S_LotteryHistoryGroup_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 记录组. + /// + public static string S_QuickDrawHistoryGroup { + get { + return ResourceManager.GetString("S_QuickDrawHistoryGroup", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 选中后闪抽只按该组的历史计算权重,本次记录也只写进该组;选「默认记录组」表示只算未分组的记录. + /// + public static string S_QuickDrawHistoryGroup_D { + get { + return ResourceManager.GetString("S_QuickDrawHistoryGroup_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 默认记录组. + /// + public static string O_HistoryGroupDefault { + get { + return ResourceManager.GetString("O_HistoryGroupDefault", resourceCulture); + } + } + + + + /// + /// Looks up a localized string similar to 随机数抽取. + /// + public static string Page_RandomNumber { + get { + return ResourceManager.GetString("Page_RandomNumber", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 默认范围与个数. + /// + public static string Section_RandomNumber_Defaults { + get { + return ResourceManager.GetString("Section_RandomNumber_Defaults", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 点名默认范围. + /// + public static string S_RandomNumber_RollCallRange { + get { + return ResourceManager.GetString("S_RandomNumber_RollCallRange", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 打开点名页时默认使用的数字范围,起点不小于 0,跨度最多 200. + /// + public static string S_RandomNumber_RollCallRange_D { + get { + return ResourceManager.GetString("S_RandomNumber_RollCallRange_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 点名默认个数. + /// + public static string S_RandomNumber_RollCallCount { + get { + return ResourceManager.GetString("S_RandomNumber_RollCallCount", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 打开点名页时默认抽取的数字个数. + /// + public static string S_RandomNumber_RollCallCount_D { + get { + return ResourceManager.GetString("S_RandomNumber_RollCallCount_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 抽奖默认范围. + /// + public static string S_RandomNumber_LotteryRange { + get { + return ResourceManager.GetString("S_RandomNumber_LotteryRange", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 打开抽奖页时默认使用的数字范围,起点不小于 0,跨度最多 200. + /// + public static string S_RandomNumber_LotteryRange_D { + get { + return ResourceManager.GetString("S_RandomNumber_LotteryRange_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 抽奖默认个数. + /// + public static string S_RandomNumber_LotteryCount { + get { + return ResourceManager.GetString("S_RandomNumber_LotteryCount", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 打开抽奖页时默认抽取的数字个数. + /// + public static string S_RandomNumber_LotteryCount_D { + get { + return ResourceManager.GetString("S_RandomNumber_LotteryCount_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 至. + /// + public static string C_RandomNumber_To { + get { + return ResourceManager.GetString("C_RandomNumber_To", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 重置行为. + /// + public static string S_RandomNumber_ResetBehavior { + get { + return ResourceManager.GetString("S_RandomNumber_ResetBehavior", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 重置随机数抽取时如何处理统计. + /// + public static string S_RandomNumber_ResetBehavior_D { + get { + return ResourceManager.GetString("S_RandomNumber_ResetBehavior_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 只清临时剩余. + /// + public static string O_RandomNumber_ResetTemporaryOnly { + get { + return ResourceManager.GetString("O_RandomNumber_ResetTemporaryOnly", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 同时清除统计. + /// + public static string O_RandomNumber_ResetTemporaryAndStatistics { + get { + return ResourceManager.GetString("O_RandomNumber_ResetTemporaryAndStatistics", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 抽取规则. + /// + public static string Section_RandomNumber_Rules { + get { + return ResourceManager.GetString("Section_RandomNumber_Rules", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 每个数字等概率抽取,重复规则沿用点名或抽奖页当前设置,范围跨度上限 200,名单历史不受随机数重置影响. + /// + public static string M_RandomNumber_Rules { + get { + return ResourceManager.GetString("M_RandomNumber_Rules", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 随机数统计. + /// + public static string Section_RandomNumber_Statistics { + get { + return ResourceManager.GetString("Section_RandomNumber_Statistics", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 累计统计. + /// + public static string S_RandomNumber_Statistics { + get { + return ResourceManager.GetString("S_RandomNumber_Statistics", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 只统计提交成功的数字抽取,最多保留最近 100 次记录. + /// + public static string S_RandomNumber_Statistics_D { + get { + return ResourceManager.GetString("S_RandomNumber_Statistics_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 累计轮次. + /// + public static string M_RandomNumber_TotalRounds { + get { + return ResourceManager.GetString("M_RandomNumber_TotalRounds", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 累计数字. + /// + public static string M_RandomNumber_TotalDrawnCount { + get { + return ResourceManager.GetString("M_RandomNumber_TotalDrawnCount", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 清除统计. + /// + public static string C_RandomNumber_ClearStatistics { + get { + return ResourceManager.GetString("C_RandomNumber_ClearStatistics", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 暂无统计. + /// + public static string M_RandomNumber_NoStatistics { + get { + return ResourceManager.GetString("M_RandomNumber_NoStatistics", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 编排抽取. + /// + public static string O_Orchestrated { + get { + return ResourceManager.GetString("O_Orchestrated", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Page_Orchestration. + /// + public static string Page_Orchestration { + get { + return ResourceManager.GetString("Page_Orchestration", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to S_Orchestration_List_D. + /// + public static string S_Orchestration_List_D { + get { + return ResourceManager.GetString("S_Orchestration_List_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to C_Orchestration_New. + /// + public static string C_Orchestration_New { + get { + return ResourceManager.GetString("C_Orchestration_New", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to C_Orchestration_Sync. + /// + public static string C_Orchestration_Sync { + get { + return ResourceManager.GetString("C_Orchestration_Sync", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to C_Orchestration_Shuffle. + /// + public static string C_Orchestration_Shuffle { + get { + return ResourceManager.GetString("C_Orchestration_Shuffle", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to C_Orchestration_Delete. + /// + public static string C_Orchestration_Delete { + get { + return ResourceManager.GetString("C_Orchestration_Delete", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to S_Orchestration_Target. + /// + public static string S_Orchestration_Target { + get { + return ResourceManager.GetString("S_Orchestration_Target", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to S_Orchestration_Source. + /// + public static string S_Orchestration_Source { + get { + return ResourceManager.GetString("S_Orchestration_Source", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to S_Orchestration_Name. + /// + public static string S_Orchestration_Name { + get { + return ResourceManager.GetString("S_Orchestration_Name", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to C_Orchestration_Create. + /// + public static string C_Orchestration_Create { + get { + return ResourceManager.GetString("C_Orchestration_Create", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to C_Orchestration_Cancel. + /// + public static string C_Orchestration_Cancel { + get { + return ResourceManager.GetString("C_Orchestration_Cancel", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to S_Orchestration_Round. + /// + public static string S_Orchestration_Round { + get { + return ResourceManager.GetString("S_Orchestration_Round", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to S_Orchestration_RoundCount. + /// + public static string S_Orchestration_RoundCount { + get { + return ResourceManager.GetString("S_Orchestration_RoundCount", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to S_Orchestration_Round_D. + /// + public static string S_Orchestration_Round_D { + get { + return ResourceManager.GetString("S_Orchestration_Round_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to C_Orchestration_Order. + /// + public static string C_Orchestration_Order { + get { + return ResourceManager.GetString("C_Orchestration_Order", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to C_Orchestration_Name. + /// + public static string C_Orchestration_Name { + get { + return ResourceManager.GetString("C_Orchestration_Name", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to C_Orchestration_Excluded. + /// + public static string C_Orchestration_Excluded { + get { + return ResourceManager.GetString("C_Orchestration_Excluded", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to C_Orchestration_Skipped. + /// + public static string C_Orchestration_Skipped { + get { + return ResourceManager.GetString("C_Orchestration_Skipped", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to C_Orchestration_Position. + /// + public static string C_Orchestration_Position { + get { + return ResourceManager.GetString("C_Orchestration_Position", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to C_Orchestration_Weight. + /// + public static string C_Orchestration_Weight { + get { + return ResourceManager.GetString("C_Orchestration_Weight", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to C_Orchestration_Note. + /// + public static string C_Orchestration_Note { + get { + return ResourceManager.GetString("C_Orchestration_Note", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to C_Orchestration_Empty. + /// + public static string C_Orchestration_Empty { + get { + return ResourceManager.GetString("C_Orchestration_Empty", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to C_Orchestration_Empty_D. + /// + public static string C_Orchestration_Empty_D { + get { + return ResourceManager.GetString("C_Orchestration_Empty_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to C_Orchestration_Enable. + /// + public static string C_Orchestration_Enable { + get { + return ResourceManager.GetString("C_Orchestration_Enable", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to C_Orchestration_Disable. + /// + public static string C_Orchestration_Disable { + get { + return ResourceManager.GetString("C_Orchestration_Disable", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to C_Orchestration_AddMember. + /// + public static string C_Orchestration_AddMember { + get { + return ResourceManager.GetString("C_Orchestration_AddMember", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to C_Orchestration_AddPrize. + /// + public static string C_Orchestration_AddPrize { + get { + return ResourceManager.GetString("C_Orchestration_AddPrize", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to O_Orchestration_TargetRollCall. + /// + public static string O_Orchestration_TargetRollCall { + get { + return ResourceManager.GetString("O_Orchestration_TargetRollCall", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to O_Orchestration_TargetLottery. + /// + public static string O_Orchestration_TargetLottery { + get { + return ResourceManager.GetString("O_Orchestration_TargetLottery", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to C_Orchestration_Active. + /// + public static string C_Orchestration_Active { + get { + return ResourceManager.GetString("C_Orchestration_Active", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to C_Orchestration_SourceMissing. + /// + public static string C_Orchestration_SourceMissing { + get { + return ResourceManager.GetString("C_Orchestration_SourceMissing", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to C_Orchestration_Members. + /// + public static string C_Orchestration_Members { + get { + return ResourceManager.GetString("C_Orchestration_Members", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to C_Orchestration_Arrange. + /// + public static string C_Orchestration_Arrange { + get { + return ResourceManager.GetString("C_Orchestration_Arrange", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to C_Orchestration_Arrange_D. + /// + public static string C_Orchestration_Arrange_D { + get { + return ResourceManager.GetString("C_Orchestration_Arrange_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to C_Orchestration_Edit. + /// + public static string C_Orchestration_Edit { + get { + return ResourceManager.GetString("C_Orchestration_Edit", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to C_Orchestration_CopyOrder. + /// + public static string C_Orchestration_CopyOrder { + get { + return ResourceManager.GetString("C_Orchestration_CopyOrder", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to C_Orchestration_ClearOrder. + /// + public static string C_Orchestration_ClearOrder { + get { + return ResourceManager.GetString("C_Orchestration_ClearOrder", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to C_Orchestration_RandomFill. + /// + public static string C_Orchestration_RandomFill { + get { + return ResourceManager.GetString("C_Orchestration_RandomFill", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to C_Orchestration_Excluded_D. + /// + public static string C_Orchestration_Excluded_D { + get { + return ResourceManager.GetString("C_Orchestration_Excluded_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to C_Orchestration_Skipped_D. + /// + public static string C_Orchestration_Skipped_D { + get { + return ResourceManager.GetString("C_Orchestration_Skipped_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to C_Orchestration_Position_D. + /// + public static string C_Orchestration_Position_D { + get { + return ResourceManager.GetString("C_Orchestration_Position_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to C_Orchestration_Weight_D. + /// + public static string C_Orchestration_Weight_D { + get { + return ResourceManager.GetString("C_Orchestration_Weight_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to S_Orchestration_EditMember. + /// + public static string S_Orchestration_EditMember { + get { + return ResourceManager.GetString("S_Orchestration_EditMember", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to S_Orchestration_EditPrize. + /// + public static string S_Orchestration_EditPrize { + get { + return ResourceManager.GetString("S_Orchestration_EditPrize", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to S_Orchestration_ProfileNew. + /// + public static string S_Orchestration_ProfileNew { + get { + return ResourceManager.GetString("S_Orchestration_ProfileNew", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to S_Orchestration_ProfileEdit. + /// + public static string S_Orchestration_ProfileEdit { + get { + return ResourceManager.GetString("S_Orchestration_ProfileEdit", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to C_Orchestration_Save. + /// + public static string C_Orchestration_Save { + get { + return ResourceManager.GetString("C_Orchestration_Save", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to M_Orchestration_SourceRequired. + /// + public static string M_Orchestration_SourceRequired { + get { + return ResourceManager.GetString("M_Orchestration_SourceRequired", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to M_Orchestration_NoSource. + /// + public static string M_Orchestration_NoSource { + get { + return ResourceManager.GetString("M_Orchestration_NoSource", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to M_Orchestration_DeleteTitle. + /// + public static string M_Orchestration_DeleteTitle { + get { + return ResourceManager.GetString("M_Orchestration_DeleteTitle", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to M_Orchestration_DeleteContent. + /// + public static string M_Orchestration_DeleteContent { + get { + return ResourceManager.GetString("M_Orchestration_DeleteContent", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to M_Orchestration_DeletePrimary. + /// + public static string M_Orchestration_DeletePrimary { + get { + return ResourceManager.GetString("M_Orchestration_DeletePrimary", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to M_Orchestration_Created. + /// + public static string M_Orchestration_Created { + get { + return ResourceManager.GetString("M_Orchestration_Created", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to M_Orchestration_Saved. + /// + public static string M_Orchestration_Saved { + get { + return ResourceManager.GetString("M_Orchestration_Saved", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to M_Orchestration_Deleted. + /// + public static string M_Orchestration_Deleted { + get { + return ResourceManager.GetString("M_Orchestration_Deleted", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to S_Orchestration_Lists. + /// + public static string S_Orchestration_Lists { + get { + return ResourceManager.GetString("S_Orchestration_Lists", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to C_Orchestration_ProfileSettings. + /// + public static string C_Orchestration_ProfileSettings { + get { + return ResourceManager.GetString("C_Orchestration_ProfileSettings", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to S_Orchestration_Profile_D. + /// + public static string S_Orchestration_Profile_D { + get { + return ResourceManager.GetString("S_Orchestration_Profile_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to S_Orchestration_Name_D. + /// + public static string S_Orchestration_Name_D { + get { + return ResourceManager.GetString("S_Orchestration_Name_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to S_Orchestration_Source_D. + /// + public static string S_Orchestration_Source_D { + get { + return ResourceManager.GetString("S_Orchestration_Source_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to S_Orchestration_Sync_D. + /// + public static string S_Orchestration_Sync_D { + get { + return ResourceManager.GetString("S_Orchestration_Sync_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to S_Orchestration_Progress. + /// + public static string S_Orchestration_Progress { + get { + return ResourceManager.GetString("S_Orchestration_Progress", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to S_Orchestration_Position_D. + /// + public static string S_Orchestration_Position_D { + get { + return ResourceManager.GetString("S_Orchestration_Position_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to S_Orchestration_Weight_D. + /// + public static string S_Orchestration_Weight_D { + get { + return ResourceManager.GetString("S_Orchestration_Weight_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to S_Orchestration_ChannelRollCall. + /// + public static string S_Orchestration_ChannelRollCall { + get { + return ResourceManager.GetString("S_Orchestration_ChannelRollCall", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to S_Orchestration_ChannelLottery. + /// + public static string S_Orchestration_ChannelLottery { + get { + return ResourceManager.GetString("S_Orchestration_ChannelLottery", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to S_Orchestration_ChannelOn. + /// + public static string S_Orchestration_ChannelOn { + get { + return ResourceManager.GetString("S_Orchestration_ChannelOn", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to S_Orchestration_ChannelOff. + /// + public static string S_Orchestration_ChannelOff { + get { + return ResourceManager.GetString("S_Orchestration_ChannelOff", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to S_Orchestration_ProfileInactive. + /// + public static string S_Orchestration_ProfileInactive { + get { + return ResourceManager.GetString("S_Orchestration_ProfileInactive", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to C_Orchestration_UseOrchestrated. + /// + public static string C_Orchestration_UseOrchestrated { + get { + return ResourceManager.GetString("C_Orchestration_UseOrchestrated", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to M_Orchestration_ChannelSwitched. + /// + public static string M_Orchestration_ChannelSwitched { + get { + return ResourceManager.GetString("M_Orchestration_ChannelSwitched", resourceCulture); + } + } + + + /// + /// Looks up a localized string similar to S_Orchestration_SectionLists. + /// + public static string S_Orchestration_SectionLists { + get { + return ResourceManager.GetString("S_Orchestration_SectionLists", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to S_Orchestration_SectionLists_D. + /// + public static string S_Orchestration_SectionLists_D { + get { + return ResourceManager.GetString("S_Orchestration_SectionLists_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to S_Orchestration_Exclude. + /// + public static string S_Orchestration_Exclude { + get { + return ResourceManager.GetString("S_Orchestration_Exclude", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to S_Orchestration_Exclude_D. + /// + public static string S_Orchestration_Exclude_D { + get { + return ResourceManager.GetString("S_Orchestration_Exclude_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to S_Orchestration_Weight. + /// + public static string S_Orchestration_Weight { + get { + return ResourceManager.GetString("S_Orchestration_Weight", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to S_Orchestration_Defer. + /// + public static string S_Orchestration_Defer { + get { + return ResourceManager.GetString("S_Orchestration_Defer", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to S_Orchestration_Defer_D. + /// + public static string S_Orchestration_Defer_D { + get { + return ResourceManager.GetString("S_Orchestration_Defer_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to S_Orchestration_Order. + /// + public static string S_Orchestration_Order { + get { + return ResourceManager.GetString("S_Orchestration_Order", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to S_Orchestration_Order_D. + /// + public static string S_Orchestration_Order_D { + get { + return ResourceManager.GetString("S_Orchestration_Order_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to S_Orchestration_Guarantee. + /// + public static string S_Orchestration_Guarantee { + get { + return ResourceManager.GetString("S_Orchestration_Guarantee", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to S_Orchestration_Guarantee_D. + /// + public static string S_Orchestration_Guarantee_D { + get { + return ResourceManager.GetString("S_Orchestration_Guarantee_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to C_Orchestration_RuleOpen. + /// + public static string C_Orchestration_RuleOpen { + get { + return ResourceManager.GetString("C_Orchestration_RuleOpen", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to C_Orchestration_RuleOff. + /// + public static string C_Orchestration_RuleOff { + get { + return ResourceManager.GetString("C_Orchestration_RuleOff", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to C_Orchestration_ProfileSummary. + /// + public static string C_Orchestration_ProfileSummary { + get { + return ResourceManager.GetString("C_Orchestration_ProfileSummary", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to C_Orchestration_ExcludeSummary. + /// + public static string C_Orchestration_ExcludeSummary { + get { + return ResourceManager.GetString("C_Orchestration_ExcludeSummary", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to C_Orchestration_WeightSummary. + /// + public static string C_Orchestration_WeightSummary { + get { + return ResourceManager.GetString("C_Orchestration_WeightSummary", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to C_Orchestration_DeferSummary. + /// + public static string C_Orchestration_DeferSummary { + get { + return ResourceManager.GetString("C_Orchestration_DeferSummary", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to C_Orchestration_OrderSummary. + /// + public static string C_Orchestration_OrderSummary { + get { + return ResourceManager.GetString("C_Orchestration_OrderSummary", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to C_Orchestration_OrderSummaryEmpty. + /// + public static string C_Orchestration_OrderSummaryEmpty { + get { + return ResourceManager.GetString("C_Orchestration_OrderSummaryEmpty", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to C_Orchestration_GuaranteeSummary. + /// + public static string C_Orchestration_GuaranteeSummary { + get { + return ResourceManager.GetString("C_Orchestration_GuaranteeSummary", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to S_Orchestration_SectionEnabled. + /// + public static string S_Orchestration_SectionEnabled { + get { + return ResourceManager.GetString("S_Orchestration_SectionEnabled", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to S_Orchestration_Rules. + /// + public static string S_Orchestration_Rules { + get { + return ResourceManager.GetString("S_Orchestration_Rules", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to S_Orchestration_Rules_D. + /// + public static string S_Orchestration_Rules_D { + get { + return ResourceManager.GetString("S_Orchestration_Rules_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to S_Orchestration_Rules_Exclude_D. + /// + public static string S_Orchestration_Rules_Exclude_D { + get { + return ResourceManager.GetString("S_Orchestration_Rules_Exclude_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to S_Orchestration_Rules_Weight_D. + /// + public static string S_Orchestration_Rules_Weight_D { + get { + return ResourceManager.GetString("S_Orchestration_Rules_Weight_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to S_Orchestration_Rules_Defer_D. + /// + public static string S_Orchestration_Rules_Defer_D { + get { + return ResourceManager.GetString("S_Orchestration_Rules_Defer_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to S_Orchestration_Rules_Order_D. + /// + public static string S_Orchestration_Rules_Order_D { + get { + return ResourceManager.GetString("S_Orchestration_Rules_Order_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to S_Orchestration_Rules_Guarantee_D. + /// + public static string S_Orchestration_Rules_Guarantee_D { + get { + return ResourceManager.GetString("S_Orchestration_Rules_Guarantee_D", resourceCulture); + } + } + + + + /// + /// Looks up a localized string similar to S_Rule_Round. + /// + public static string S_Rule_Round { + get { + return ResourceManager.GetString("S_Rule_Round", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to S_Rule_Disabled. + /// + public static string S_Rule_Disabled { + get { + return ResourceManager.GetString("S_Rule_Disabled", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to S_Rule_Count. + /// + public static string S_Rule_Count { + get { + return ResourceManager.GetString("S_Rule_Count", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to C_Rule_Search. + /// + public static string C_Rule_Search { + get { + return ResourceManager.GetString("C_Rule_Search", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to C_Rule_Shuffle. + /// + public static string C_Rule_Shuffle { + get { + return ResourceManager.GetString("C_Rule_Shuffle", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to C_Rule_CopyOrder. + /// + public static string C_Rule_CopyOrder { + get { + return ResourceManager.GetString("C_Rule_CopyOrder", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to C_Rule_ClearList. + /// + public static string C_Rule_ClearList { + get { + return ResourceManager.GetString("C_Rule_ClearList", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to C_Rule_MoveUp. + /// + public static string C_Rule_MoveUp { + get { + return ResourceManager.GetString("C_Rule_MoveUp", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to C_Rule_MoveDown. + /// + public static string C_Rule_MoveDown { + get { + return ResourceManager.GetString("C_Rule_MoveDown", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to C_Rule_WeightWatermark. + /// + public static string C_Rule_WeightWatermark { + get { + return ResourceManager.GetString("C_Rule_WeightWatermark", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to C_Rule_NoMembers. + /// + public static string C_Rule_NoMembers { + get { + return ResourceManager.GetString("C_Rule_NoMembers", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to C_Rule_NoProfile. + /// + public static string C_Rule_NoProfile { + get { + return ResourceManager.GetString("C_Rule_NoProfile", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to C_Rule_Profile. + /// + public static string C_Rule_Profile { + get { + return ResourceManager.GetString("C_Rule_Profile", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to C_Rule_NoProfile_D. + /// + public static string C_Rule_NoProfile_D { + get { + return ResourceManager.GetString("C_Rule_NoProfile_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to C_Rule_NoMembers_D. + /// + public static string C_Rule_NoMembers_D { + get { + return ResourceManager.GetString("C_Rule_NoMembers_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to C_Rule_NoMatch_D. + /// + public static string C_Rule_NoMatch_D { + get { + return ResourceManager.GetString("C_Rule_NoMatch_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to C_Rule_ExcludeHint_D. + /// + public static string C_Rule_ExcludeHint_D { + get { + return ResourceManager.GetString("C_Rule_ExcludeHint_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to C_Rule_WeightHint_D. + /// + public static string C_Rule_WeightHint_D { + get { + return ResourceManager.GetString("C_Rule_WeightHint_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to C_Rule_DeferHint_D. + /// + public static string C_Rule_DeferHint_D { + get { + return ResourceManager.GetString("C_Rule_DeferHint_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to C_Rule_OrderHint_D. + /// + public static string C_Rule_OrderHint_D { + get { + return ResourceManager.GetString("C_Rule_OrderHint_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to C_Rule_GuaranteeHint_D. + /// + public static string C_Rule_GuaranteeHint_D { + get { + return ResourceManager.GetString("C_Rule_GuaranteeHint_D", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to C_Rule_ToggleExclude. + /// + public static string C_Rule_ToggleExclude { + get { + return ResourceManager.GetString("C_Rule_ToggleExclude", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to C_Rule_ToggleDefer. + /// + public static string C_Rule_ToggleDefer { + get { + return ResourceManager.GetString("C_Rule_ToggleDefer", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to C_Rule_ToggleOrder. + /// + public static string C_Rule_ToggleOrder { + get { + return ResourceManager.GetString("C_Rule_ToggleOrder", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to C_Rule_ToggleGuarantee. + /// + public static string C_Rule_ToggleGuarantee { + get { + return ResourceManager.GetString("C_Rule_ToggleGuarantee", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to C_Rule_ExcludeNote. + /// + public static string C_Rule_ExcludeNote { + get { + return ResourceManager.GetString("C_Rule_ExcludeNote", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to C_Rule_NotInQueue. + /// + public static string C_Rule_NotInQueue { + get { + return ResourceManager.GetString("C_Rule_NotInQueue", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to C_Rule_NotGuaranteed. + /// + public static string C_Rule_NotGuaranteed { + get { + return ResourceManager.GetString("C_Rule_NotGuaranteed", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to M_Rule_Shuffled. + /// + public static string M_Rule_Shuffled { + get { + return ResourceManager.GetString("M_Rule_Shuffled", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to M_Rule_OrderCopied. + /// + public static string M_Rule_OrderCopied { + get { + return ResourceManager.GetString("M_Rule_OrderCopied", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to M_Rule_Cleared. + /// + public static string M_Rule_Cleared { + get { + return ResourceManager.GetString("M_Rule_Cleared", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to M_Rule_ConflictTitle. + /// + public static string M_Rule_ConflictTitle { + get { + return ResourceManager.GetString("M_Rule_ConflictTitle", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to M_Rule_ConflictContent. + /// + public static string M_Rule_ConflictContent { + get { + return ResourceManager.GetString("M_Rule_ConflictContent", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to M_Rule_ConflictRound. + /// + public static string M_Rule_ConflictRound { + get { + return ResourceManager.GetString("M_Rule_ConflictRound", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to C_Rule_Continue. + /// + public static string C_Rule_Continue { + get { + return ResourceManager.GetString("C_Rule_Continue", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to M_Rule_ConflictSwitchTitle. + /// + public static string M_Rule_ConflictSwitchTitle { + get { + return ResourceManager.GetString("M_Rule_ConflictSwitchTitle", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to M_Rule_ConflictSwitchContent. + /// + public static string M_Rule_ConflictSwitchContent { + get { + return ResourceManager.GetString("M_Rule_ConflictSwitchContent", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to C_Rule_ReplaceOrder. + /// + public static string C_Rule_ReplaceOrder { + get { + return ResourceManager.GetString("C_Rule_ReplaceOrder", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to M_Rule_ShuffleConflict. + /// + public static string M_Rule_ShuffleConflict { + get { + return ResourceManager.GetString("M_Rule_ShuffleConflict", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to M_Rule_CopyConflict. + /// + public static string M_Rule_CopyConflict { + get { + return ResourceManager.GetString("M_Rule_CopyConflict", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to C_Rule_ConflictJoin. + /// + public static string C_Rule_ConflictJoin { + get { + return ResourceManager.GetString("C_Rule_ConflictJoin", resourceCulture); + } + } + + } +} diff --git a/SecRandom/Langs/SettingsPages/Picking/Resources.en-US.resx b/SecRandom/Langs/SettingsPages/Picking/Resources.en-US.resx index 7948f3fe2..6e643943a 100644 --- a/SecRandom/Langs/SettingsPages/Picking/Resources.en-US.resx +++ b/SecRandom/Langs/SettingsPages/Picking/Resources.en-US.resx @@ -1,116 +1,540 @@ - - - text/microsoft-resx - 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 - Default Draw Settings - Roll-call Draw Settings - Quick Draw Settings - Lottery Draw Settings - Draw Settings - Display Settings - Animation Settings - Color Settings - Member Image Settings - Reminder Settings - Enable Override - Draw Mode - Controls how repeated draw records are handled - Half-repeat Threshold - After this number of draws, the item will not re-enter the candidate pool - Clear Records - Controls when draw records are cleared - Draw Method - Choose random or fair drawing - Lottery Method - Choose drawing by prize wheel or remaining quantity - Default Member List - The list used by default when opening a page or running Quick Draw - Default Prize Pool - The prize pool used by default when opening the lottery page - No roster - Disable After Click - Seconds to disable the button after a Quick Draw - Show drawing status - Show the drawing status line while a Quick Draw is running; when off the window stays steady until the result lands - Font Source - Follow the global font or specify a font for draw results - Custom Font - Font family name; leave empty to use the default font - Font Size - Text size for draw results - Display Format - Choose whether results show names, numbers, or both - Display Style - Controls the overall style of draw results - Lottery Process Display - Display format for candidate results during the lottery - Show Tags - Show member or prize tags in draw results - Show Weight Transparency - Show weight information in the result display - Reminder Text - Text shown beside the result area on draw pages - Reminder Font Size - Reminder text size - Reminder Color - Reminder text color - Reminder Opacity - Reminder text opacity (0-100) - Animation Mode - Set how the draw animation plays - Animation Interval - Interval between draw animation changes (milliseconds) - Autoplay Count - Number of candidate result changes in autoplay mode - Animation Style - Unified animation effect for the draw process and final result - Color Theme - Set the source of colors for draw animations and results - Fixed Color - Used when the color theme is fixed color - Show Member Images - Show member images in draw results - Image Position - Position of the member image relative to the text - Allow RepeatsNo RepeatsHalf RepeatClear on RestartClear ManuallyRandom DrawNo MusicRandom PlaybackExternal file: {0}Unavailable: {0}Fair DrawBy Prize WheelBy Remaining QuantityFollow GlobalCustomNumber and NameName OnlyNumber OnlyDefaultCardManual StopAutoplayNo AnimationDirect RotationFade and Float UpHorizontal ShakeNoneRandomFixed ColorLeftTopRightBottom - Prize/Group-NamePrize/Group/NamePrize-Group-NamePrize/NamePrize-NamePrize/GroupPrize-Group - Overridable SettingsMusic SettingsVoice AnnouncementEnable Voice AnnouncementAnnounce results after a draw; ineffective when global voice announcements are disabledAnimation MusicMusic used while the draw animation playsLoop Animation MusicRepeat animation music while the animation continuesResult MusicMusic used when the draw result appearsMusic VolumeSet the animation and result music volume in orderMusic Fade In and OutSet animation fade-in, animation fade-out, result fade-in, and result fade-out times (milliseconds)Animation Music VolumeSet the animation music volumeResult Music VolumeSet the result music volumeAnimation Music Fade In and OutTop slider controls fade-in, bottom slider controls fade-out, in millisecondsResult Music Fade In and OutTop slider controls fade-in, bottom slider controls fade-out, in millisecondsFade InFade OutPrize Image SettingsShow Prize ImagesShow prize images in lottery resultsPrize Image PositionPosition of the prize image relative to the textBatch Set AvatarsBatch match and set avatars from the first-level images of the chosen directory by record name or numberImages are only searched in the first level of the chosen directoryChoose DirectoryRoll-call RosterTarget Roll-call RosterTarget Lottery RosterLottery RosterRe-select external fileSetRecordAvatar File{0} records auto-matchedCancelOKPlease choose a directory containing images firstAvatar file not found: {0}Avatars set for {0} recordsNo directory selectedSet Roll-call Roster AvatarsOpen the roll-call roster page and set member avatars through the Show Image attached settingSet Lottery Roster AvatarsOpen the lottery roster page and set prize images through the Show Image attached setting - Image Size - Display edge length of member images in draw results, in pixels - Prize Image Size - Display edge length of prize images in draw results, in pixels - Record group - When a group is picked, the roll-call page starts on that group and computes weights from its history alone; pick Default record group to count only ungrouped records - Record group - When a group is picked, the lottery page starts on that group and computes weights from its history alone; pick Default record group to count only ungrouped records - Record group - When a group is picked, Quick Draw computes weights from that group's history alone and writes this draw's records into it as well; pick Default record group to count only ungrouped records - Default record group - Record groups are not enabled; turn them on in History management - Random numbers - Default ranges - Roll-call default range - Number range applied when the roll-call page opens - Roll-call default count - Number of values drawn by default when the roll-call page opens - Lottery default range - Number range applied when the lottery page opens - Lottery default count - Number of values drawn by default when the lottery page opens - to - What reset clears - Reset only affects drawn numbers and random-number statistics; roll-call and lottery roster history is always kept - Drawn numbers only - Drawn numbers and random-number statistics - Draw Rules - Every number is drawn with equal probability, repeat rules follow the current roll-call or lottery page, the span limit is 200, and roster history is never changed by a random-number reset - Random-number Statistics - Cumulative statistics - Only committed number draws are counted; the most recent 100 records are kept - Total rounds - Total numbers - Clear statistics - No statistics yet - + + + text/microsoft-resx + 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 + Default Draw Settings + Roll-call Draw Settings + Quick Draw Settings + Lottery Draw Settings + Draw Settings + Display Settings + Animation Settings + Color Settings + Member Image Settings + Reminder Settings + Enable Override + Draw Mode + Controls how repeated draw records are handled + Half-repeat Threshold + After this number of draws, the item will not re-enter the candidate pool + Clear Records + Controls when draw records are cleared + Draw Method + Choose random, fair, or orchestrated drawing + Fair Draw Strategy + Uniform first draws only members at or below the average count; random first weights by the least-drawn member and caps any lead at two draws + Uniform first + Random first + Lottery Method + Choose drawing by prize wheel or remaining quantity + Default Member List + The list used by default when opening a page or running Quick Draw + Default Prize Pool + The prize pool used by default when opening the lottery page + Random numbers + Disable After Click + Seconds to disable the button after a Quick Draw + Show drawing status + Show the drawing status line while a Quick Draw is running; when off the window stays steady until the result lands + Font Source + Follow the global font or specify a font for draw results + Custom Font + Font family name; leave empty to use the default font + Font Size + Text size for draw results + Display Format + Choose whether results show names, numbers, or both + Display Style + Controls the overall style of draw results + Lottery Process Display + Display format for candidate results during the lottery + Show Tags + Show member or prize tags in draw results + Show Weight Transparency + Show weight information in the result display + Reminder Text + Text shown beside the result area on draw pages + Reminder Font Size + Reminder text size + Reminder Color + Reminder text color + Reminder Opacity + Reminder text opacity (0-100) + Animation Mode + Set how the draw animation plays + Animation Interval + Interval between draw animation changes (milliseconds) + Autoplay Count + Number of candidate result changes in autoplay mode + Animation Style + Unified animation effect for the draw process and final result + Color Theme + Set the source of colors for draw animations and results + Fixed Color + Used when the color theme is fixed color + Show Member Images + Show member images in draw results + Image Position + Position of the member image relative to the text + Allow RepeatsNo RepeatsHalf RepeatOrchestratedClear on RestartClear ManuallyRandom DrawNo MusicRandom PlaybackExternal file: {0}Unavailable: {0}Fair DrawBy Prize WheelBy Remaining QuantityFollow GlobalCustomNumber and NameName OnlyNumber OnlyDefaultCardManual StopAutoplayNo AnimationDirect RotationFade and Float UpHorizontal ShakeNoneRandomFixed ColorLeftTopRightBottom + Prize/Group-NamePrize/Group/NamePrize-Group-NamePrize/NamePrize-NamePrize/GroupPrize-Group + Overridable SettingsMusic SettingsVoice AnnouncementEnable Voice AnnouncementAnnounce results after a draw; ineffective when global voice announcements are disabledAnimation MusicMusic used while the draw animation playsLoop Animation MusicRepeat animation music while the animation continuesResult MusicMusic used when the draw result appearsMusic VolumeSet the animation and result music volume in orderMusic Fade In and OutSet animation fade-in, animation fade-out, result fade-in, and result fade-out times (milliseconds)Animation Music VolumeSet the animation music volumeResult Music VolumeSet the result music volumeAnimation Music Fade In and OutTop slider controls fade-in, bottom slider controls fade-out, in millisecondsResult Music Fade In and OutTop slider controls fade-in, bottom slider controls fade-out, in millisecondsFade InFade OutPrize Image SettingsShow Prize ImagesShow prize images in lottery resultsPrize Image PositionPosition of the prize image relative to the textBatch Set AvatarsBatch match and set avatars from the first-level images of the chosen directory by record name or numberImages are only searched in the first level of the chosen directoryChoose DirectoryRoll-call RosterTarget Roll-call RosterTarget Lottery RosterLottery RosterRe-select external fileSetRecordAvatar File{0} records auto-matchedCancelOKPlease choose a directory containing images firstAvatar file not found: {0}Avatars set for {0} recordsNo directory selectedSet Roll-call Roster AvatarsOpen the roll-call roster page and set member avatars through the Show Image attached settingSet Lottery Roster AvatarsOpen the lottery roster page and set prize images through the Show Image attached setting + Image Size + Display edge length of member images in draw results, in pixels + Prize Image Size + Display edge length of prize images in draw results, in pixels + Record group + When a group is picked, the roll-call page starts on that group and computes weights from its history alone; pick Default record group to count only ungrouped records + Record group + When a group is picked, the lottery page starts on that group and computes weights from its history alone; pick Default record group to count only ungrouped records + Record group + When a group is picked, Quick Draw computes weights from that group's history alone and writes this draw's records into it as well; pick Default record group to count only ungrouped records + Default record group + + Random numbers + Default ranges + Roll-call default range + Number range applied when the roll-call page opens + Roll-call default count + Number of values drawn by default when the roll-call page opens + Lottery default range + Number range applied when the lottery page opens + Lottery default count + Number of values drawn by default when the lottery page opens + to + What reset clears + Reset only affects drawn numbers and random-number statistics; roll-call and lottery roster history is always kept + Drawn numbers only + Drawn numbers and random-number statistics + Draw Rules + Every number is drawn with equal probability, repeat rules follow the current roll-call or lottery page, the span limit is 200, and roster history is never changed by a random-number reset + Random-number Statistics + Cumulative statistics + Only committed number draws are counted; the most recent 100 records are kept + Total rounds + Total numbers + Clear statistics + No statistics yet + + Orchestration Draw + + + Each orchestration list binds one draw channel and one source list, matched automatically + + + New + + + Sync list + + + Shuffle order + + + Delete + + + Draw channel + + + Source list + + + List name + + + Create + + + Cancel + + + Round + + + Rounds + + + One round means everyone appears once; a reset also counts, up to 10 rounds + + + Order + + + Name + + + Excluded + + + Skipped this round + + + Draw position + + + Weight + + + Note + + + No orchestration list yet + + + Create one first: pick a draw channel and a source list, members come in automatically + + + Enable + + + Disable + + + Add arranged member + + + Add arranged prize + + + Roll call + + + Lottery + + + Active + + + Not in source list + + + Clear this round's order + + + Edit arranged prize + + + Edit arranged member + + + Skip this round only + + + Random fill + + + Members + + + Drag a row up or down to change this round's order + + + Relative chance before the order is fixed + + + Arrange order + + + Edit + + + Copy to other rounds + + + e.g. 3 means drawn third this round + + + Never in this list + + + Orchestration lists + + + List settings + + + Save + + + New orchestration list + + + Edit orchestration list + + + An orchestration list binds one draw channel and one source list, and starts with every member + + + Blank names are generated as source list · draw channel + + + Switching the source list never deletes members, it flags the missing ones + + + Adds members the list does not carry yet, leaving the arrangement alone + + + The draw has reached round {0} + + + This draw channel has no list yet, create one in list management first + + + Delete orchestration list + + + Deleting "{0}" removes its whole arrangement and cannot be undone + + + Delete + + + Created orchestration list "{0}" + + + Saved orchestration list "{0}" + + + Deleted orchestration list "{0}" + + + Choose a source list first + + + e.g. 3 draws this member third, applied when you leave the box + + + Weight multiplier before the order is fixed, applied when you leave the box + + + Roll-call draw channel + + + Lottery draw channel + + + already orchestrated, so this list applies in its arranged order + + + not orchestrated right now, so this list has no effect + + + This list is not active yet, so draws will not use it + + + Use orchestrated draw + + + Switched the draw mode to orchestrated + + + Five lists + + + Each list does one thing and is edited on its own page + + + Excluded + + + Members here sit out the whole arrangement + + + Weight + + + Deferred + + + Skipped this round, back to normal next round + + + Ordered + + + This round's queue: drawn members leave and the rest move up + + + Guaranteed + + + Must appear this round, placed first + + + Settings + + + Off + + + {0} · {1} · {2} members + + + {0} excluded · {1} still take part + + + {0} with a manual weight + + + {0} deferred this round + + + {0} in this round's queue + + + No order yet this round, drawn by weight + + + {0} guaranteed this round + + + Turn lists on + + + List switches + + + A list that is off keeps its contents; the draw stops reading it + + + Off: they take part as usual + + + Off: fair weight only + + + Off: nobody is pushed to the tail + + + Off: weighted draw instead + + + Off: not scheduled first + + + Round + + + This list is switched off on the overview page, so nothing here affects the draw yet + + + ({0} members, {1} on this list) + + + Search number or name + + + Shuffle + + + Copy to other rounds + + + Clear this list + + + Move up + + + Move down + + + Default + + + No members to show + + + No arrangement selected + + + Arrangement: {0} ({1} · {2}) + + + Pick an arrangement on the orchestrated draw overview first + + + Sync the source roster on the overview page to bring members in + + + No member matches, try another keyword + + + Checked members sit out the whole arrangement + + + Weight multiplier for this round, blank means fair weight + + + Checked members go to the tail this round and return next round + + + Check to join the tail, use the arrows to reorder, drawn members leave + + + Checked members go first this round + + + Sit out + + + Defer this round + + + Join the queue + + + Guaranteed this round + + + On the exclusion list + + + Not in the queue + + + Not guaranteed + + + Shuffled this round's queue + + + Copied this queue to the other {0} rounds + + + Cleared "{0}" + + + Other lists will be cancelled + + + Adding to {0} cancels this member's entries in {1} + + + round {0} · {1} + + + Continue + + + Another list will be turned off + + + Turning on {0} turns off {1} + + + Replace queue + + + Shuffling rebuilds the queue, so guaranteed members are removed from it + + + Copying overwrites the other rounds and removes their guaranteed members from the queue + + + , + + diff --git a/SecRandom/Langs/SettingsPages/Picking/Resources.ja-JP.resx b/SecRandom/Langs/SettingsPages/Picking/Resources.ja-JP.resx index 08332b00a..e5c46a554 100644 --- a/SecRandom/Langs/SettingsPages/Picking/Resources.ja-JP.resx +++ b/SecRandom/Langs/SettingsPages/Picking/Resources.ja-JP.resx @@ -1,612 +1,1045 @@ - - - - text/microsoft-resx - - - 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 - - - 既定の抽選設定 - - - 点呼抽選設定 - - - クイック抽選設定 - - - くじ引き抽選設定 - - - 抽選設定 - - - 表示設定 - - - アニメーション設定 - - - 色設定 - - - メンバー画像設定 - - - リマインダー設定 - - - 上書きを有効化 - - - 抽選モード - - - 重複する抽選記録の扱いを指定します - - - 半重複のしきい値 - - - この回数抽選された項目は候補に戻りません - - - 記録を消去 - - - 抽選記録を消去するタイミングを指定します - - - 抽選方法 - - - ランダム抽選または公平な抽選を選択します - - - くじ引き方法 - - - くじ盤または残り個数による抽選を選択します - - - 既定のメンバーリスト - - - ページを開くとき、またはクイック抽選時に使う名簿 - - - 既定の景品プール - - - くじ引きページを開くときに使う景品プール - - - 乱数 - - - クリック後の無効時間 - - - クイック抽選後にボタンを無効にする秒数 - - - 抽選中のステータスを表示 - - - クイック抽選の実行中に「抽選中」を表示します。オフにすると結果が出るまで画面は前回の内容のまま変わりません - - - フォントの指定元 - - - 全体設定に従うか、抽選結果専用のフォントを指定します - - - カスタムフォント - - - フォントファミリー名を指定し、空欄の場合は既定のフォントを使用します - - - フォントサイズ - - - 抽選結果の文字サイズ - - - 表示形式 - - - 結果に名称、番号、または両方を表示するか指定します - - - 表示スタイル - - - 抽選結果全体のスタイルを指定します - - - 抽選中の表示 - - - 抽選中に候補結果を表示する形式 - - - タグを表示 - - - 抽選結果にメンバーまたは景品のタグを表示します - - - 重みを表示 - - - 結果表示に重みの情報を表示します - - - リマインダー - - - 抽選ページの結果欄の横に表示する文字 - - - リマインダーの文字サイズ - - - リマインダーの文字サイズ - - - リマインダーの色 - - - リマインダーの文字色 - - - リマインダーの不透明度 - - - リマインダーの不透明度(0-100) - - - アニメーションモード - - - 抽選アニメーションの再生方法 - - - アニメーション間隔 - - - 抽選アニメーションの切り替え間隔(ミリ秒) - - - 自動再生回数 - - - 自動再生時に候補結果を切り替える回数 - - - アニメーションスタイル - - - 抽選中と最終結果に使用する統一アニメーション - - - カラーテーマ - - - 抽選アニメーションと結果の色の指定元 - - - 固定色 - - - 固定色のテーマで使用します - - - 画像を表示 - - - 抽選結果にメンバー画像を表示します - - - 画像の位置 - - - 文字に対するメンバー画像の位置 - - - 画像サイズ - - - 抽選結果に表示するメンバー画像の一辺の長さ(ピクセル) - - - 重複を許可 - - - 重複なし - - - 半重複 - - - 再起動後に消去 - - - 手動で消去 - - - ランダム抽選 - - - 音楽なし - - - ランダム再生 - - - 外部ファイル: {0} - - - 利用不可: {0} - - - 公平な抽選 - - - くじ盤による - - - 残り個数による - - - 全体設定に従う - - - カスタム - - - 番号と名称 - - - 名称のみ - - - 番号のみ - - - 既定 - - - カード - - - 手動停止 - - - 自動再生 - - - アニメーションなし - - - 直接切り替え - - - フェードして上昇 - - - 左右に揺らす - - - なし - - - ランダム - - - 固定色 - - - 左 - - - 上 - - - 右 - - - 下 - - - 景品/分組-名称 - - - 景品/分組/名称 - - - 景品-分組-名称 - - - 景品/名称 - - - 景品-名称 - - - 景品/分組 - - - 景品-分組 - - - 上書き可能な設定 - - - 音楽設定 - - - 音声案内 - - - 音声案内を有効化 - - - 抽選後に結果を読み上げ、全体の音声案内が無効の場合は機能しません - - - アニメーション音楽 - - - 抽選アニメーション中に再生する音楽 - - - アニメーション音楽をループ - - - アニメーション中に音楽を繰り返します - - - 結果音楽 - - - 抽選結果の表示時に再生する音楽 - - - 音楽の音量 - - - アニメーション音楽と結果音楽の音量 - - - 音楽のフェード - - - アニメーションのフェードイン、フェードアウト、結果音楽のフェードイン、フェードアウト時間(ミリ秒) - - - アニメーション音楽の音量 - - - アニメーション音楽の音量 - - - 結果音楽の音量 - - - 結果音楽の音量 - - - アニメーション音楽のフェード - - - 上のスライダーがフェードイン、下がフェードアウト(ミリ秒) - - - 結果音楽のフェード - - - 上のスライダーがフェードイン、下がフェードアウト(ミリ秒) - - - フェードイン - - - フェードアウト - - - 景品画像設定 - - - 景品画像を表示 - - - くじ引き結果に景品画像を表示します - - - 景品画像の位置 - - - 文字に対する景品画像の位置 - - - 景品画像サイズ - - - くじ引き結果に表示する景品画像の一辺の長さ(ピクセル) - - - アバターを一括設定 - - - 記録の名称または番号を基に、選択したディレクトリの第1階層の画像からアバターを一括マッチングして設定します - - - 画像は選択したディレクトリの第1階層のみを対象にします - - - ディレクトリを選択 - - - 点呼名簿 - - - 対象の点呼名簿 - - - 対象のくじ引き名簿 - - - くじ引き名簿 - - - 外部ファイルを再選択 - - - 設定 - - - 記録 - - - アバターファイル - - - 自動マッチング {0} 件 - - - キャンセル - - - OK - - - 先に画像を含むディレクトリを選択してください - - - アバターファイルが見つかりません: {0} - - - {0} 件の記録にアバターを設定しました - - - ディレクトリ未選択 - - - 点呼名簿のアバターを設定 - - - 点呼名簿ページを開き、メンバーの追加設定(画像表示)でアバターを設定します - - - くじ引き名簿のアバターを設定 - - - くじ引き名簿ページを開き、景品の追加設定(画像表示)で景品画像を設定します - - - 記録グループ - - - グループを選ぶと点名ページはそのグループを初期選択にし、重みはそのグループの記録だけを参照、既定の記録グループなら未分類の記録だけを数えます - - - 記録グループ - - - グループを選ぶと抽選ページはそのグループを初期選択にし、重みはそのグループの記録だけを参照、既定の記録グループなら未分類の記録だけを数えます - - - 記録グループ - - - グループを選ぶとクイック抽選はそのグループの履歴だけで重みを計算し、今回の記録もそのグループにのみ書き込みます、既定の記録グループなら未分類の記録だけを数えます - - - 既定の記録グループ - - - 履歴記録グループ機能が有効になっていません、「履歴記録の管理」で有効にできます - - - 乱数抽選 - - - 既定の範囲 - - - 点呼の既定範囲 - - - 点呼ページを開くときの既定の数値範囲 - - - 点呼の既定個数 - - - 点呼ページを開くときに既定で抽選する数値の個数 - - - 抽選の既定範囲 - - - 抽選ページを開くときの既定の数値範囲 - - - 抽選の既定個数 - - - 抽選ページを開くときに既定で抽選する数値の個数 - - - から - - - リセットで消去する内容 - - - リセットは乱数抽選の抽選済み数字と統計だけを対象にし、点呼と抽選の名簿履歴は常に保持します - - - 抽選済みの数字のみ - - - 抽選済みの数字と乱数統計 - - - 抽選ルール - - - 各数値は等確率で抽選され、重複ルールは現在の点呼または抽選ページの設定に従い、範囲の幅の上限は 200 です、名簿履歴は乱数抽選のリセットでは変更されません - - - 乱数の統計 - - - 累計統計 - - - コミットされた数値抽選だけを集計し、直近 100 件まで保持します - - - 累計回数 - - - 累計数値 - - - 統計を消去 - - - 統計はまだありません - - + + + + text/microsoft-resx + + + 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 + + + 既定の抽選設定 + + + 点呼抽選設定 + + + クイック抽選設定 + + + くじ引き抽選設定 + + + 抽選設定 + + + 表示設定 + + + アニメーション設定 + + + 色設定 + + + メンバー画像設定 + + + リマインダー設定 + + + 上書きを有効化 + + + 抽選モード + + + 重複する抽選記録の扱いを指定します + + + 半重複のしきい値 + + + この回数抽選された項目は候補に戻りません + + + 記録を消去 + + + 抽選記録を消去するタイミングを指定します + + + 抽選方法 + + + ランダム抽選、公平な抽選、編成抽選から選択します + + + 公平抽選の方針 + + + 均等優先は平均回数以下のメンバーだけを抽選し、ランダム優先は最少回数のメンバーを基準に重み付けして二回を超える先行を許しません + + + 均等優先 + + + ランダム優先 + + + くじ引き方法 + + + くじ盤または残り個数による抽選を選択します + + + 既定のメンバーリスト + + + ページを開くとき、またはクイック抽選時に使う名簿 + + + 既定の景品プール + + + くじ引きページを開くときに使う景品プール + + + 乱数 + + + クリック後の無効時間 + + + クイック抽選後にボタンを無効にする秒数 + + + 抽選中のステータスを表示 + + + クイック抽選の実行中に「抽選中」を表示します。オフにすると結果が出るまで画面は前回の内容のまま変わりません + + + フォントの指定元 + + + 全体設定に従うか、抽選結果専用のフォントを指定します + + + カスタムフォント + + + フォントファミリー名を指定し、空欄の場合は既定のフォントを使用します + + + フォントサイズ + + + 抽選結果の文字サイズ + + + 表示形式 + + + 結果に名称、番号、または両方を表示するか指定します + + + 表示スタイル + + + 抽選結果全体のスタイルを指定します + + + 抽選中の表示 + + + 抽選中に候補結果を表示する形式 + + + タグを表示 + + + 抽選結果にメンバーまたは景品のタグを表示します + + + 重みを表示 + + + 結果表示に重みの情報を表示します + + + リマインダー + + + 抽選ページの結果欄の横に表示する文字 + + + リマインダーの文字サイズ + + + リマインダーの文字サイズ + + + リマインダーの色 + + + リマインダーの文字色 + + + リマインダーの不透明度 + + + リマインダーの不透明度(0-100) + + + アニメーションモード + + + 抽選アニメーションの再生方法 + + + アニメーション間隔 + + + 抽選アニメーションの切り替え間隔(ミリ秒) + + + 自動再生回数 + + + 自動再生時に候補結果を切り替える回数 + + + アニメーションスタイル + + + 抽選中と最終結果に使用する統一アニメーション + + + カラーテーマ + + + 抽選アニメーションと結果の色の指定元 + + + 固定色 + + + 固定色のテーマで使用します + + + 画像を表示 + + + 抽選結果にメンバー画像を表示します + + + 画像の位置 + + + 文字に対するメンバー画像の位置 + + + 画像サイズ + + + 抽選結果に表示するメンバー画像の一辺の長さ(ピクセル) + + + 重複を許可 + + + 重複なし + + + 半重複 + + + 編成抽選 + + + 再起動後に消去 + + + 手動で消去 + + + ランダム抽選 + + + 音楽なし + + + ランダム再生 + + + 外部ファイル: {0} + + + 利用不可: {0} + + + 公平な抽選 + + + くじ盤による + + + 残り個数による + + + 全体設定に従う + + + カスタム + + + 番号と名称 + + + 名称のみ + + + 番号のみ + + + 既定 + + + カード + + + 手動停止 + + + 自動再生 + + + アニメーションなし + + + 直接切り替え + + + フェードして上昇 + + + 左右に揺らす + + + なし + + + ランダム + + + 固定色 + + + 左 + + + 上 + + + 右 + + + 下 + + + 景品/分組-名称 + + + 景品/分組/名称 + + + 景品-分組-名称 + + + 景品/名称 + + + 景品-名称 + + + 景品/分組 + + + 景品-分組 + + + 上書き可能な設定 + + + 音楽設定 + + + 音声案内 + + + 音声案内を有効化 + + + 抽選後に結果を読み上げ、全体の音声案内が無効の場合は機能しません + + + アニメーション音楽 + + + 抽選アニメーション中に再生する音楽 + + + アニメーション音楽をループ + + + アニメーション中に音楽を繰り返します + + + 結果音楽 + + + 抽選結果の表示時に再生する音楽 + + + 音楽の音量 + + + アニメーション音楽と結果音楽の音量 + + + 音楽のフェード + + + アニメーションのフェードイン、フェードアウト、結果音楽のフェードイン、フェードアウト時間(ミリ秒) + + + アニメーション音楽の音量 + + + アニメーション音楽の音量 + + + 結果音楽の音量 + + + 結果音楽の音量 + + + アニメーション音楽のフェード + + + 上のスライダーがフェードイン、下がフェードアウト(ミリ秒) + + + 結果音楽のフェード + + + 上のスライダーがフェードイン、下がフェードアウト(ミリ秒) + + + フェードイン + + + フェードアウト + + + 景品画像設定 + + + 景品画像を表示 + + + くじ引き結果に景品画像を表示します + + + 景品画像の位置 + + + 文字に対する景品画像の位置 + + + 景品画像サイズ + + + くじ引き結果に表示する景品画像の一辺の長さ(ピクセル) + + + アバターを一括設定 + + + 記録の名称または番号を基に、選択したディレクトリの第1階層の画像からアバターを一括マッチングして設定します + + + 画像は選択したディレクトリの第1階層のみを対象にします + + + ディレクトリを選択 + + + 点呼名簿 + + + 対象の点呼名簿 + + + 対象のくじ引き名簿 + + + くじ引き名簿 + + + 外部ファイルを再選択 + + + 設定 + + + 記録 + + + アバターファイル + + + 自動マッチング {0} 件 + + + キャンセル + + + OK + + + 先に画像を含むディレクトリを選択してください + + + アバターファイルが見つかりません: {0} + + + {0} 件の記録にアバターを設定しました + + + ディレクトリ未選択 + + + 点呼名簿のアバターを設定 + + + 点呼名簿ページを開き、メンバーの追加設定(画像表示)でアバターを設定します + + + くじ引き名簿のアバターを設定 + + + くじ引き名簿ページを開き、景品の追加設定(画像表示)で景品画像を設定します + + + 記録グループ + + + グループを選ぶと点名ページはそのグループを初期選択にし、重みはそのグループの記録だけを参照、既定の記録グループなら未分類の記録だけを数えます + + + 記録グループ + + + グループを選ぶと抽選ページはそのグループを初期選択にし、重みはそのグループの記録だけを参照、既定の記録グループなら未分類の記録だけを数えます + + + 記録グループ + + + グループを選ぶとクイック抽選はそのグループの履歴だけで重みを計算し、今回の記録もそのグループにのみ書き込みます、既定の記録グループなら未分類の記録だけを数えます + + + 既定の記録グループ + + + + 乱数抽選 + + + 既定の範囲 + + + 点呼の既定範囲 + + + 点呼ページを開くときの既定の数値範囲 + + + 点呼の既定個数 + + + 点呼ページを開くときに既定で抽選する数値の個数 + + + 抽選の既定範囲 + + + 抽選ページを開くときの既定の数値範囲 + + + 抽選の既定個数 + + + 抽選ページを開くときに既定で抽選する数値の個数 + + + から + + + リセットで消去する内容 + + + リセットは乱数抽選の抽選済み数字と統計だけを対象にし、点呼と抽選の名簿履歴は常に保持します + + + 抽選済みの数字のみ + + + 抽選済みの数字と乱数統計 + + + 抽選ルール + + + 各数値は等確率で抽選され、重複ルールは現在の点呼または抽選ページの設定に従い、範囲の幅の上限は 200 です、名簿履歴は乱数抽選のリセットでは変更されません + + + 乱数の統計 + + + 累計統計 + + + コミットされた数値抽選だけを集計し、直近 100 件まで保持します + + + 累計回数 + + + 累計数値 + + + 統計を消去 + + + 統計はまだありません + + + 編成抽選設定 + + + 各編成名簿は1つの抽選チャンネルと1つの参照名簿に紐づき、抽選時に自動で一致します + + + 新規 + + + 名簿を同期 + + + 順序をシャッフル + + + 削除 + + + 抽選チャンネル + + + 参照名簿 + + + 名簿名 + + + 作成 + + + キャンセル + + + ラウンド + + + ラウンド数 + + + 1ラウンド=全員が1回ずつ出場、途中リセットも1ラウンドと数え、最大10ラウンド + + + 順序 + + + 名前 + + + 除外 + + + 今回延期 + + + 何番目 + + + 重み + + + 備考 + + + 編成名簿はまだありません + + + まず編成名簿を作成してください、抽選チャンネルと参照名簿を選ぶとメンバーは自動で取り込まれます + + + 有効化 + + + 無効化 + + + 編成メンバーを追加 + + + 編成景品を追加 + + + 点名 + + + 抽選 + + + 有効 + + + 参照名簿に存在しません + + + この回の順序を消去 + + + 編成賞品を編集 + + + 編成メンバーを編集 + + + この回だけ後回し + + + ランダム補充 + + + メンバー表 + + + 行を上下にドラッグするとこの回の出場順を調整できます + + + 順位が未定のときの当たりやすさ + + + 順序配置 + + + 編集 + + + 他の回へコピー + + + 例: 3 ならこの回の 3 番目 + + + この名簿では常に除外 + + + 編成名簿 + + + 名簿設定 + + + 保存 + + + 編成名簿を作成 + + + 編成名簿を編集 + + + 編成名簿は1つの抽選チャンネルと1つの参照名簿に紐づき、作成時に全メンバーを取り込みます + + + 空欄の場合は「参照名簿・抽選チャンネル」で自動命名 + + + 参照名簿を変えてもメンバーは削除されず、新しい名簿にない人が「参照名簿に存在しません」と表示されます + + + 参照名簿からまだ入っていないメンバーを追加し、既存の並びは変更しません + + + 抽選は第 {0} ラウンドまで進んでいます + + + この抽選チャンネルにはまだ名簿がありません。先に名簿管理で作成してください + + + 編成名簿を削除 + + + 編成名簿「{0}」とその並びをすべて削除します。元に戻せません + + + 削除 + + + 編成名簿「{0}」を作成しました + + + 編成名簿「{0}」を保存しました + + + 編成名簿「{0}」を削除しました + + + 先に参照名簿を選択してください + + + 例:3 ならこのラウンドで3番目、入力欄から離れると反映されます + + + 順位が未定のときの重みの倍率、入力欄から離れると反映されます + + + 点呼の抽選チャンネル + + + 景品抽選のチャンネル + + + すでに編成抽選です、この名簿は組み立てた順に使われます + + + 現在は編成抽選ではないため、この名簿は使われません + + + この名簿はまだ有効になっていないため、抽選には使われません + + + 編成抽選に切り替える + + + 抽選方式を編成抽選に切り替えました + + + 5つのリスト + + + 各リストは1つの役割だけを持ち、それぞれの設定ページで編集します + + + 除外リスト + + + ここに入れた人は編成全体で参加しません + + + 重みリスト + + + 後回しリスト + + + この回だけ後回しにし、次の回で戻ります + + + 順番リスト + + + この回の出場キュー、引かれた人は抜けて後ろが詰まります + + + 必中リスト + + + この回に必ず出場し、先頭に並びます + + + 設定 + + + オフ + + + {0} · {1} · {2} 人 + + + {0} 人を除外 · 残り {1} 人は通常参加 + + + {0} 人に手動重みあり + + + この回の後回し {0} 人 + + + この回のキュー {0} 人 + + + この回は未設定のため重みで抽選 + + + この回の必中 {0} 人 + + + リストの有効化 + + + リストのスイッチ + + + オフにしたリストは内容を保持しますが、抽選では読まれません + + + オフにすると通常どおり参加します + + + オフにすると公平重みのみ + + + オフにすると末尾に回されません + + + オフにすると重みで抽選します + + + オフにすると先頭に置きません + + + 回 + + + 概要ページでこのリストがオフのため、ここの内容はまだ抽選に影響しません + + + ({0} 人、このリスト {1} 人) + + + 番号か名前で検索 + + + ランダム順 + + + 他の回へコピー + + + このリストを空にする + + + 上へ + + + 下へ + + + 既定 + + + 表示できるメンバーがいません + + + 編成リストが未選択 + + + 編成リスト:{0}({1} · {2}) + + + 先に編成抽選の概要でリストを選んでください + + + 先に概要ページで参照名簿を同期してください + + + 一致するメンバーがいません、別のキーワードを試してください + + + チェックした人は編成全体で抽選に参加しません + + + この回の重みの倍率、空欄は公平重み + + + チェックした人はこの回だけ末尾に回り、次の回で戻ります + + + チェックで末尾に追加、矢印で並べ替え、引かれた人は抜けます + + + チェックした人はこの回に先頭で出場します + + + 不参加 + + + この回は後回し + + + キューに入れる + + + この回は必中 + + + 除外リストにあり + + + キュー未加入 + + + 必中リスト未加入 + + + この回のキューを並べ替えました + + + このキューの内容を残り {0} 回へコピーしました + + + 「{0}」を空にしました + + + 他のリストが解除されます + + + {0}に追加すると、この人の{1}の記録が解除されます + + + 第{0}回 {1} + + + 続行 + + + 別のリストがオフになります + + + {0}をオンにすると{1}がオフになります + + + キューを置き換える + + + ランダム順はキューを組み直すため、必中リストの人はキューから外れます + + + キューのコピーは他の回を上書きし、それらの回の必中リストの人をキューから外します + + + 、 + + diff --git a/SecRandom/Langs/SettingsPages/Picking/Resources.resx b/SecRandom/Langs/SettingsPages/Picking/Resources.resx index 02d1ef503..6c47f4f72 100644 --- a/SecRandom/Langs/SettingsPages/Picking/Resources.resx +++ b/SecRandom/Langs/SettingsPages/Picking/Resources.resx @@ -1,384 +1,807 @@ - - - text/microsoft-resx - 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 - 默认抽取设置 - 点名抽取设置 - 闪抽抽取设置 - 抽奖抽取设置 - 抽取设置 - 显示设置 - 动画设置 - 颜色设置 - 成员头像设置 - 提示语设置 - 启用覆盖 - 抽取模式 - 控制重复抽取记录的处理方式 - 半重复阈值 - 抽中次数达到该值后不会再次进入候选池 - 清除记录 - 控制抽取记录何时清除 - 抽取方式 - 设置使用随机抽取或公平抽取 - 抽奖方式 - 设置按奖盘或按剩余数量抽奖 - 抽奖算法 - 选择用于生成奖品候选池的算法 - 点名算法 - 选择用于生成成员候选池的算法 - 点名算法 - 选择闪抽使用的点名算法 - 公平抽取 - 随机抽取 - 按剩余数量 - 加权抽奖 - 默认抽取名单 - 打开页面或执行闪抽时默认使用的名单 - 默认抽奖名单 - 打开抽奖页时默认使用的奖池 - 随机数 - 点击后禁用时间 - 点击一次闪抽后禁用按钮的秒数 - 显示抽取中状态 - 在闪抽窗口显示“正在抽取”,关闭后抽取期间画面保持上一轮内容,结果落定才刷新 - 字体来源 - 跟随全局字体或为抽取结果单独指定字体 - 自定义字体 - 字体族名称,留空时使用默认字体 - 字体大小 - 抽取结果文字大小 - 显示格式 - 控制结果中显示名称、编号或两者 - 显示样式 - 控制抽取结果的整体样式 - 抽奖过程显示 - 抽奖过程中候选结果的展示格式 - 自定义显示格式 - 设置抽奖过程的自定义展示格式 - 插入格式变量 - 支持使用以下格式化变量,点按变量即可插入: - 序号 - 奖项 - 奖项 ID - 奖项名称 - 成员 - 成员 ID - 成员名字 - 成员分组 - 格式 - 换行 - 除换行符以外,其他分隔符可直接输入 - 显示标签 - 抽取结果中展示成员或奖品标签 - 权重透明化 - 在结果展示中显示权重透明信息 - 提示语 - 抽取页结果区域旁显示的提示文字 - 提示语字体大小 - 提示语文字大小 - 提示语颜色 - 提示语文字颜色 - 提示语透明度 - 提示语文字透明度(0-100) - 动画模式 - 设置抽取动画播放方式 - 动画间隔 - 抽取动画每次切换的间隔(毫秒) - 自动播放次数 - 自动播放模式下滚动候选结果的次数 - 动画样式 - 设置抽取过程和最终定格时使用的统一动画效果 - 颜色主题 - 设置抽取动画和结果颜色来源 - 固定颜色 - 颜色主题为固定颜色时使用 - 显示头像 - 在抽取结果中显示成员头像 - 头像位置 - 成员头像相对文字的位置 - 头像大小 - 抽取结果中头像的显示边长,单位为像素 - 允许重复 - 不重复 - 半重复 - 重启后清除 - 手动清除 - 随机抽取 - 不开启音乐 - 随机播放 - 外部文件:{0} - 不可用:{0} - 公平抽取 - 按奖盘 - 按剩余数量 - 跟随全局 - 自定义 - 编号和名称 - 仅名称 - 仅编号 - 默认 - 卡片 - 手动停止 - 自动播放 - 无动画 - 直接轮换 - 淡入上浮 - 左右晃动 - - - 无 - 随机 - 固定颜色 - 左侧 - 上方 - 右侧 - 下方 - 奖品/分组-名称 - 序号 奖品/分组-名称 - 奖品/分组/名称 - 奖品-分组-名称 - 奖品/名称 - 奖品-名称 - 奖品/分组 - 奖品-分组 - - 可覆盖设置 - - - 音乐设置 - - - 语音播报 - - - 启用语音播报 - - - 抽取完成后播报结果;全局语音播报开关关闭时,此设置不会生效 - - - 动画音乐 - - - 选择抽取动画播放时使用的音乐 - - 循环播放动画音乐 - 动画持续期间重复播放动画音乐 - - 结果音乐 - - - 选择抽取结果出现时使用的音乐 - - - 音乐音量 - - - 依次设置动画音乐和结果音乐的音量 - - - 音乐淡入淡出 - - - 依次设置动画音乐淡入、动画音乐淡出、结果音乐淡入和结果音乐淡出时间(毫秒) - - 动画音乐音量 - 设置抽取动画音乐的音量 - 结果音乐音量 - 设置抽取结果音乐的音量 - 动画音乐淡入和淡出 - 上方滑块控制淡入,下方滑块控制淡出,单位为毫秒 - 结果音乐淡入和淡出 - 上方滑块控制淡入,下方滑块控制淡出,单位为毫秒 - 淡入 - 淡出 - - 奖品图片设置 - - - 显示奖品图片 - - - 在抽奖结果中显示奖品图片 - - - 奖品图片位置 - - - 奖品图片相对文字的位置 - - - 奖品图片大小 - - - 抽奖结果中奖品图片的显示边长,单位为像素 - - - 批量设置头像 - - - 根据记录的名称或编号,从所选目录的第一层图片中批量匹配并设置头像 - - - 图片只从所选目录的第一层查找 - - - 选择目录 - - - 点名名单 - - - 指定点名名单 - - - 指定抽奖名单 - - - 抽奖名单 - - - 重新选择外部文件 - - - 设置 - - - 记录 - - - 头像文件 - - - 自动匹配 {0} 条记录 - - - 取消 - - - 确定 - - - 请先选择包含图片的目录 - - - 找不到头像文件:{0} - - - 已为 {0} 条记录设置头像 - - - 未选择目录 - - - 设置点名名单头像 - - - 前往点名名单页面,用成员附加设置「展示图片」设置头像 - - - 设置抽奖名单头像 - - - 前往抽奖名单页面,用奖品附加设置「展示图片」设置奖品图片 - - - 记录组 - - - 选中后点名页默认按该组的历史计算权重,本次记录也只写进该组;选「默认记录组」表示只算未分组的记录 - - - 记录组 - - - 选中后抽奖页默认按该组的历史计算权重,本次记录也只写进该组;选「默认记录组」表示只算未分组的记录 - - - 记录组 - - - 选中后闪抽只按该组的历史计算权重,本次记录也只写进该组;选「默认记录组」表示只算未分组的记录 - - - 默认记录组 - - - 历史记录组功能未启用,可在「历史记录管理」里打开 - - - 随机数抽取 - - - 默认范围 - - - 点名默认范围 - - - 打开点名页时默认使用的数字范围 - - - 点名默认个数 - - - 打开点名页时默认抽取的数字个数 - - - 抽奖默认范围 - - - 打开抽奖页时默认使用的数字范围 - - - 抽奖默认个数 - - - 打开抽奖页时默认抽取的数字个数 - - - 至 - - - 重置时清除什么 - - - 重置只处理随机数抽取的已抽数字和统计,点名与抽奖名单历史始终保留 - - - 只清除已抽数字 - - - 同时清除随机数统计 - - - 抽取规则 - - - 每个数字等概率抽取,重复规则沿用点名或抽奖页当前设置,范围跨度上限 200,名单历史不受随机数重置影响 - - - 随机数统计 - - - 累计统计 - - - 只统计提交成功的数字抽取,最多保留最近 100 次记录 - - - 累计轮次 - - - 累计数字 - - - 清除统计 - - - 暂无统计 - - + + + text/microsoft-resx + 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 + 默认抽取设置 + 点名抽取设置 + 闪抽抽取设置 + 抽奖抽取设置 + 抽取设置 + 显示设置 + 动画设置 + 颜色设置 + 成员头像设置 + 提示语设置 + 启用覆盖 + 抽取模式 + 控制重复抽取记录的处理方式 + 半重复阈值 + 抽中次数达到该值后不会再次进入候选池 + 清除记录 + 控制抽取记录何时清除 + 抽取方式 + 设置使用随机抽取、公平抽取或编排抽取 + 公平抽取策略 + 均匀优先只抽平均次数及以下的成员,随机优先按最少次数加权,最多领先两次 + 均匀优先 + 随机优先 + 抽奖方式 + 设置按奖盘或按剩余数量抽奖 + 抽奖算法 + 选择奖品候选池的抽取方式,也可以选编排抽取按编排名单取奖 + 点名算法 + 选择用于生成成员候选池的算法 + 点名算法 + 选择闪抽使用的点名算法 + 公平抽取 + 随机抽取 + 按剩余数量 + 加权抽奖 + 默认抽取名单 + 打开页面或执行闪抽时默认使用的名单 + 默认抽奖名单 + 打开抽奖页时默认使用的奖池 + 随机数 + 点击后禁用时间 + 点击一次闪抽后禁用按钮的秒数 + 显示抽取中状态 + 在闪抽窗口显示“正在抽取”,关闭后抽取期间画面保持上一轮内容,结果落定才刷新 + 字体来源 + 跟随全局字体或为抽取结果单独指定字体 + 自定义字体 + 字体族名称,留空时使用默认字体 + 字体大小 + 抽取结果文字大小 + 显示格式 + 控制结果中显示名称、编号或两者 + 显示样式 + 控制抽取结果的整体样式 + 抽奖过程显示 + 抽奖过程中候选结果的展示格式 + 自定义显示格式 + 设置抽奖过程的自定义展示格式 + 插入格式变量 + 支持使用以下格式化变量,点按变量即可插入: + 序号 + 奖项 + 奖项 ID + 奖项名称 + 成员 + 成员 ID + 成员名字 + 成员分组 + 格式 + 换行 + 除换行符以外,其他分隔符可直接输入 + 显示标签 + 抽取结果中展示成员或奖品标签 + 权重透明化 + 在结果展示中显示权重透明信息 + 提示语 + 抽取页结果区域旁显示的提示文字 + 提示语字体大小 + 提示语文字大小 + 提示语颜色 + 提示语文字颜色 + 提示语透明度 + 提示语文字透明度(0-100) + 动画模式 + 设置抽取动画播放方式 + 动画间隔 + 抽取动画每次切换的间隔(毫秒) + 自动播放次数 + 自动播放模式下滚动候选结果的次数 + 动画样式 + 设置抽取过程和最终定格时使用的统一动画效果 + 颜色主题 + 设置抽取动画和结果颜色来源 + 固定颜色 + 颜色主题为固定颜色时使用 + 显示头像 + 在抽取结果中显示成员头像 + 头像位置 + 成员头像相对文字的位置 + 头像大小 + 抽取结果中头像的显示边长,单位为像素 + 允许重复 + 不重复 + 半重复 + 编排抽取 + 重启后清除 + 手动清除 + 随机抽取 + 不开启音乐 + 随机播放 + 外部文件:{0} + 不可用:{0} + 公平抽取 + 按奖盘 + 按剩余数量 + 跟随全局 + 自定义 + 编号和名称 + 仅名称 + 仅编号 + 默认 + 卡片 + 手动停止 + 自动播放 + 无动画 + 直接轮换 + 淡入上浮 + 左右晃动 + + + 无 + 随机 + 固定颜色 + 左侧 + 上方 + 右侧 + 下方 + 奖品/分组-名称 + 序号 奖品/分组-名称 + 奖品/分组/名称 + 奖品-分组-名称 + 奖品/名称 + 奖品-名称 + 奖品/分组 + 奖品-分组 + + 可覆盖设置 + + + 音乐设置 + + + 语音播报 + + + 启用语音播报 + + + 抽取完成后播报结果;全局语音播报开关关闭时,此设置不会生效 + + + 动画音乐 + + + 选择抽取动画播放时使用的音乐 + + 循环播放动画音乐 + 动画持续期间重复播放动画音乐 + + 结果音乐 + + + 选择抽取结果出现时使用的音乐 + + + 音乐音量 + + + 依次设置动画音乐和结果音乐的音量 + + + 音乐淡入淡出 + + + 依次设置动画音乐淡入、动画音乐淡出、结果音乐淡入和结果音乐淡出时间(毫秒) + + 动画音乐音量 + 设置抽取动画音乐的音量 + 结果音乐音量 + 设置抽取结果音乐的音量 + 动画音乐淡入和淡出 + 上方滑块控制淡入,下方滑块控制淡出,单位为毫秒 + 结果音乐淡入和淡出 + 上方滑块控制淡入,下方滑块控制淡出,单位为毫秒 + 淡入 + 淡出 + + 奖品图片设置 + + + 显示奖品图片 + + + 在抽奖结果中显示奖品图片 + + + 奖品图片位置 + + + 奖品图片相对文字的位置 + + + 奖品图片大小 + + + 抽奖结果中奖品图片的显示边长,单位为像素 + + + 批量设置头像 + + + 根据记录的名称或编号,从所选目录的第一层图片中批量匹配并设置头像 + + + 图片只从所选目录的第一层查找 + + + 选择目录 + + + 点名名单 + + + 指定点名名单 + + + 指定抽奖名单 + + + 抽奖名单 + + + 重新选择外部文件 + + + 设置 + + + 记录 + + + 头像文件 + + + 自动匹配 {0} 条记录 + + + 取消 + + + 确定 + + + 请先选择包含图片的目录 + + + 找不到头像文件:{0} + + + 已为 {0} 条记录设置头像 + + + 未选择目录 + + + 设置点名名单头像 + + + 前往点名名单页面,用成员附加设置「展示图片」设置头像 + + + 设置抽奖名单头像 + + + 前往抽奖名单页面,用奖品附加设置「展示图片」设置奖品图片 + + + 记录组 + + + 选中后点名页默认按该组的历史计算权重,本次记录也只写进该组;选「默认记录组」表示只算未分组的记录 + + + 记录组 + + + 选中后抽奖页默认按该组的历史计算权重,本次记录也只写进该组;选「默认记录组」表示只算未分组的记录 + + + 记录组 + + + 选中后闪抽只按该组的历史计算权重,本次记录也只写进该组;选「默认记录组」表示只算未分组的记录 + + + 默认记录组 + + + + 随机数抽取 + + + 默认范围 + + + 点名默认范围 + + + 打开点名页时默认使用的数字范围 + + + 点名默认个数 + + + 打开点名页时默认抽取的数字个数 + + + 抽奖默认范围 + + + 打开抽奖页时默认使用的数字范围 + + + 抽奖默认个数 + + + 打开抽奖页时默认抽取的数字个数 + + + 至 + + + 重置时清除什么 + + + 重置只处理随机数抽取的已抽数字和统计,点名与抽奖名单历史始终保留 + + + 只清除已抽数字 + + + 同时清除随机数统计 + + + 抽取规则 + + + 每个数字等概率抽取,重复规则沿用点名或抽奖页当前设置,范围跨度上限 200,名单历史不受随机数重置影响 + + + 随机数统计 + + + 累计统计 + + + 只统计提交成功的数字抽取,最多保留最近 100 次记录 + + + 累计轮次 + + + 累计数字 + + + 清除统计 + + + 暂无统计 + + + 编排抽取设置 + + + 每个编排名单绑定一个抽取通道和一份来源名单,抽取时自动匹配 + + + 新建 + + + 同步名单 + + + 随机顺序 + + + 删除 + + + 抽取通道 + + + 来源名单 + + + 名单名称 + + + 创建 + + + 取消 + + + 轮次 + + + 轮次数 + + + 一轮即全员各出场一次,重置也算一轮,最多 10 轮 + + + 顺序 + + + 姓名 / 奖品 + + + 排除 + + + 本轮延后 + + + 第几个抽中 + + + 权重 + + + 说明 + + + 还没有编排名单 + + + 先新建一个编排名单:选择抽取模式和来源名单,成员会自动带入 + + + 启用 + + + 停用 + + + 添加编排成员 + + + 添加编排奖品 + + + 点名 + + + 抽奖 + + + 已启用 + + + 已不在来源名单 + + + 清除本轮顺序 + + + 编辑编排奖品 + + + 编辑编排成员 + + + 只跳过这一轮 + + + 随机填充 + + + 成员表 + + + 按住行上下拖动即可调整本轮出场顺序 + + + 定序前被抽到的相对机会 + + + 顺序排布 + + + 编辑 + + + 复制到其他轮 + + + 如 3 表示本轮第 3 个抽中 + + + 本名单全局不参与 + + + 编排名单 + + + 名单设置 + + + 保存 + + + 新建编排名单 + + + 编辑编排名单 + + + 编排名单绑定一个抽取通道和一份来源名单,创建时带入全部成员 + + + 留空时按「来源名单 · 抽取通道」自动命名 + + + 换来源名单不会删除成员,只把不在新名单里的标成已失效 + + + 从来源名单补入缺少的成员,不动已有排布 + + + 抽取进行到第 {0} 轮 + + + 该抽取通道还没有名单,请先到名单管理里创建 + + + 删除编排名单 + + + 将删除编排名单「{0}」和它的全部排布,无法撤销 + + + 删除 + + + 已创建编排名单「{0}」 + + + 已保存编排名单「{0}」 + + + 已删除编排名单「{0}」 + + + 请先选择来源名单 + + + 如 3 表示本轮第 3 个抽中,离开输入框后生效 + + + 定序前的权重乘数,离开输入框后生效 + + + 点名抽取通道 + + + 抽奖抽取通道 + + + 已是编排抽取,这份名单会按排定的顺序生效 + + + 目前不是编排抽取,这份名单不会生效 + + + 这份名单还没启用,抽取不会用它 + + + 切换为编排抽取 + + + 已把抽取方式切换为编排抽取 + + + 五份名单 + + + 五份名单各管一件事,点开各自的设置页单独编 + + + 排斥名单 + + + 名单里的人整份编排名单都不参加 + + + 权重名单 + + + 延后名单 + + + 这一轮先不抽,下一轮自动恢复 + + + 顺序名单 + + + 本轮的出场队列,抽到谁谁离队 + + + 必中名单 + + + 本轮必定出场,排在最前面 + + + 设置 + + + 已关闭 + + + {0} · {1} · {2} 人 + + + 已排斥 {0} 人 · 其余 {1} 人照常参与 + + + {0} 人设了手动权重 + + + 本轮延后 {0} 人 + + + 本轮队列 {0} 人 + + + 本轮还没排顺序,按权重随机 + + + 本轮必中 {0} 人 + + + 启用名单 + + + 名单开关 + + + 关掉的名单保留内容,但抽取时不读它 + + + 关掉后照常参加 + + + 关掉后只按公平权重 + + + 关掉后不再排到队尾 + + + 关掉后按权重随机 + + + 关掉后不参与排序 + + + 轮次 + + + 总览页把这份名单的开关关了,这里的内容暂时不影响抽取 + + + ({0} 人,本名单 {1} 人) + + + 搜索学号或姓名 + + + 随机顺序 + + + 复制到其他轮 + + + 清空本名单 + + + 上移 + + + 下移 + + + 默认 + + + 没有可显示的成员 + + + 还没有选中编排名单 + + + 编排名单:{0}({1} · {2}) + + + 先在编排抽取总览里选一份名单 + + + 先在总览页同步来源名单,把成员导进来 + + + 没有匹配的成员,换个关键词试试 + + + 勾上的人整份名单都不参加抽取 + + + 这一轮的权重乘数,留空即公平权重 + + + 勾上的人这一轮排到最后,下一轮自动恢复 + + + 勾选加入队尾,用箭头调整先后,抽到谁谁离队 + + + 勾上的人这一轮排在最前面 + + + 不参加 + + + 本轮延后 + + + 加入队列 + + + 本轮必中 + + + 已在排斥名单 + + + 未加入队列 + + + 未加入必中名单 + + + 已随机重排本轮队列 + + + 已把本轮队列复制到其余 {0} 轮 + + + 已清空「{0}」 + + + 会取消其他名单 + + + 加入{0}会取消这个成员在{1}里的记录 + + + 第 {0} 轮 {1} + + + 继续 + + + 会关闭另一份名单 + + + 开启{0}会关闭{1} + + + 替换队列 + + + 随机顺序会重排队列,必中名单里的人会被移出 + + + 复制队列会覆盖其他轮,并把这些轮必中名单里的人移出 + + + 、 + + diff --git a/SecRandom/Services/Draw/SharedDrawServices.cs b/SecRandom/Services/Draw/SharedDrawServices.cs index 586e09157..e87dab0b7 100644 --- a/SecRandom/Services/Draw/SharedDrawServices.cs +++ b/SecRandom/Services/Draw/SharedDrawServices.cs @@ -7,8 +7,11 @@ using SecRandom.Core.Enums; using SecRandom.Core.Enums.Configs; using SecRandom.Core.Models.Draw; +using SecRandom.Core.Interfaces; +using SecRandom.Core.Models.Orchestration; using SecRandom.Core.Services.Config; using SecRandom.Core.Services.Draw; +using SecRandom.Core.Services.Orchestration; using SecRandom.Core.Services.Profiles; using SecRandom.Core.Services.Stats; using SecRandom.Services.Verification; @@ -61,6 +64,44 @@ public sealed record RollCallNumberSnapshot(int RangeStart, int RangeEnd, IReadO public int RemainingCount => Remaining.Count; } +/// +/// 解析「这条历史记录该盖哪个组标记」。 +/// +/// +/// 读取范围(HistoryGroup)和写入归属(RecordGroup)是两件事:读取范围为空表示“不按组筛历史”, +/// 写入则必须落在本抽取通道自己配置的默认记录组上。否则功能总开关关掉时,点名、闪抽、抽奖、编排的记录会 +/// 一起挤进默认记录组,重新打开就再也拆不回各自的组。组目录读不到时保留配置名——组名只是标记,把记录 +/// 静默挪进默认组是不可逆的信息丢失。 +/// +internal static class HistoryRecordGroup +{ + public static string Resolve( + IHistoryGroupCatalog? catalog, + ILogger logger, + HistoryGroupKind kind, + string configuredGroup, + string? readScope) + { + if (readScope is not null) + return readScope; + + IReadOnlyList? names = null; + if (catalog is not null) + { + try + { + names = catalog.GetGroupNames(kind); + } + catch (Exception exception) + { + logger.LogWarning(exception, "读取历史记录组目录失败,本次按配置名写入记录组。"); + } + } + + return HistoryGroupScope.ResolveRecordGroup(configuredGroup, names); + } +} + /// /// Shared point-call use case for every UI. Presentation layers own authorization, preview and media. /// @@ -75,8 +116,14 @@ public sealed class RollCallDrawService( ILogger logger, IDrawPipelineService? pipeline = null, IPluginEventBus? eventBus = null, - IRandomNumberStatisticsService? randomNumberStatistics = null) + IRandomNumberStatisticsService? randomNumberStatistics = null, + IHistoryGroupCatalog? historyGroupCatalog = null, + IOrchestrationStore? orchestrationStore = null, + OrchestrationScheduler? orchestrationScheduler = null, + IRandomSource? randomSource = null) { + private static readonly CryptoRandomSource FallbackRandom = new(); + public RollCallDrawSnapshot GetSnapshot(string group, string gender) { var students = profileService.CurrentStudentList?.Students ?? []; @@ -117,14 +164,36 @@ public void SwitchList(string name) if (snapshot.RemainingCount == 0) return null; - var outcome = await verification.DrawStudentsAsync( - count, - snapshot.Remaining, - DrawSettingsType.RollCall, - DrawProofExportContext.ForStudents(GetListName(), request.Group, request.Gender, request.CourseName), - courseName: request.CourseName, - historyGroup: request.HistoryGroup, - cancellationToken: cancellationToken).ConfigureAwait(false); + // 编排抽取不抽样:本轮的顺序事先排定,抽取只是按序取人。没有可用编排名单时静默回退随机抽取, + // 因为主页面按要求不暴露编排状态,一个缺失的名单不该把点名按钮变成死键。 + var plan = configHandler.Data.EffectiveRollCallSettings.DrawMode == DrawMode.Orchestrated + ? PrepareOrchestration(request, snapshot) + : null; + VerificationDrawOutcome? outcome; + if (plan is not null) + { + if (plan.Order.Count == 0) + return null; + outcome = await verification.DrawOrchestratedStudentsAsync( + plan.Order.Take(count).ToArray(), + plan.Round, + plan.RoundCount, + DrawProofExportContext.ForStudents(GetListName(), request.Group, request.Gender, request.CourseName), + courseName: request.CourseName, + historyGroup: request.HistoryGroup, + cancellationToken: cancellationToken).ConfigureAwait(false); + } + else + { + outcome = await verification.DrawStudentsAsync( + count, + snapshot.Remaining, + DrawSettingsType.RollCall, + DrawProofExportContext.ForStudents(GetListName(), request.Group, request.Gender, request.CourseName), + courseName: request.CourseName, + historyGroup: request.HistoryGroup, + cancellationToken: cancellationToken).ConfigureAwait(false); + } // Every remaining member can be temporarily excluded (post-draw shield), so nothing is drawable yet. if (outcome is null) return null; @@ -143,8 +212,11 @@ public void SwitchList(string name) var weights = outcome.Winners.ToDictionary(student => student, student => { ProfileRecordIdentity.EnsureRecordId(student); - return outcome.FrozenWeights.GetValueOrDefault(student.RecordId, 1d); + // 编排的位置写在证明的权重槽里,它不是一个抽样权重,不能当权重记进结果。 + return plan is null ? outcome.FrozenWeights.GetValueOrDefault(student.RecordId, 1d) : 1d; }); + var recordGroup = HistoryRecordGroup.Resolve(historyGroupCatalog, logger, HistoryGroupKind.RollCall, + configHandler.Data.EffectiveRollCallSettings.HistoryGroup, request.HistoryGroup); var drawRoundId = edit?.SuppressHistory == true ? edit.OverrideRoundId ?? string.Empty : drawCommits.CommitStudentDraw(new StudentDrawCommit( @@ -158,7 +230,8 @@ public void SwitchList(string name) weights, request.CourseName, edit?.OverrideRoundId, - request.HistoryGroup)); + request.HistoryGroup, + recordGroup)); try { verification.Publish(outcome); @@ -168,6 +241,9 @@ public void SwitchList(string name) logger.LogWarning(exception, "点名已提交,但抽取证明发布失败,证明将保持待发布状态。ProofId={ProofId}", outcome.Proof.ProofId); } + // 一轮抽完(本轮的排布已全部出场)就推进到下一轮,并清掉本轮临时记录,否则下轮开局人人都是「已抽」。 + if (plan is not null) + AdvanceOrchestration(plan, request, Math.Min(count, plan.Order.Count)); // Counted only after the commit succeeded, so a rolled-back draw is never reported as a draw. usageReport.RecordRollCall(); // 抽签完成事件:插件可以据此记账、写自己的日志,而不必轮询历史。 @@ -184,7 +260,69 @@ public void SwitchList(string name) edit?.Note, edit?.SuppressPresentation ?? false); } - public void Reset(string group, string gender) => temporaryRecords.ClearStudentScope(GetListName(), gender, group); + public void Reset(string group, string gender) + { + // 编排里「重置」也算一轮:即使没抽完,也按用户的语义进入下一轮。 + if (configHandler.Data.EffectiveRollCallSettings.DrawMode == DrawMode.Orchestrated + && orchestrationStore is not null) + { + var profile = orchestrationStore.FindActive(OrchestrationTarget.RollCall, GetListName()).FirstOrDefault(); + if (profile is not null) + orchestrationStore.SaveRuntime(AdvanceRuntime(profile, orchestrationStore.GetRuntime(profile))); + } + + temporaryRecords.ClearStudentScope(GetListName(), gender, group); + } + + private OrchestrationPlan? PrepareOrchestration(RollCallDrawRequest request, RollCallDrawSnapshot snapshot) + { + if (orchestrationStore is null || orchestrationScheduler is null) + return null; + var profile = orchestrationStore.FindActive(OrchestrationTarget.RollCall, GetListName()).FirstOrDefault(); + if (profile is null) + return null; + + var runtime = orchestrationStore.GetRuntime(profile); + var drawn = new HashSet(); + foreach (var key in temporaryRecords.GetStudentCounts(GetListName(), request.Gender, request.Group).Keys) + { + if (Guid.TryParseExact(key, "N", out var recordId)) + drawn.Add(recordId); + } + + var order = orchestrationScheduler.OrderRound( + profile, + profile.GetRound(runtime.Round), + snapshot.Remaining, + drawn, + randomSource ?? FallbackRandom, + request.CourseName, + request.HistoryGroup); + return new OrchestrationPlan(profile, runtime.Round, profile.EffectiveRoundCount, order); + } + + private void AdvanceOrchestration(OrchestrationPlan plan, RollCallDrawRequest request, int drawnCount) + { + if (orchestrationStore is null || drawnCount < plan.Order.Count) + return; + + orchestrationStore.SaveRuntime(AdvanceRuntime(plan.Profile, orchestrationStore.GetRuntime(plan.Profile))); + // 下一轮所有人重新入池:不清掉本轮临时记录,下一轮开局就会人人被判为「已抽」。 + temporaryRecords.ClearStudentScope(GetListName(), request.Gender, request.Group); + } + + private static OrchestrationRuntime AdvanceRuntime(OrchestrationProfile profile, OrchestrationRuntime runtime) + { + runtime.Round = runtime.Round >= profile.EffectiveRoundCount ? 1 : runtime.Round + 1; + runtime.UpdatedAt = DateTime.UtcNow; + return runtime; + } + + private sealed record OrchestrationPlan( + OrchestrationProfile Profile, + int Round, + int RoundCount, + IReadOnlyList Order); /// Temporary-record scope for number draws; deliberately not a real roster name. public const string NumberListName = "__number_list__"; @@ -366,7 +504,11 @@ public sealed class LotteryDrawService( ILogger logger, IDrawPipelineService? pipeline = null, IPluginEventBus? eventBus = null, - IRandomNumberStatisticsService? randomNumberStatistics = null) + IRandomNumberStatisticsService? randomNumberStatistics = null, + IHistoryGroupCatalog? historyGroupCatalog = null, + IOrchestrationStore? orchestrationStore = null, + OrchestrationScheduler? orchestrationScheduler = null, + IRandomSource? randomSource = null) { public LotteryDrawSnapshot GetSnapshot(string studentListName, string group, string gender) { @@ -435,20 +577,45 @@ public void SwitchStudentList(string name) var count = Math.Clamp(request.Count, 1, snapshot.RemainingCount); if (hasStudentAssignment && snapshot.EligibleStudents.Count < count) return null; - var prizes = await verification.DrawPrizesAsync(count, - temporaryRecords.GetPrizeCounts(GetPrizePoolName()), snapshot.Prizes, - DrawProofExportContext.ForPrizes(GetPrizePoolName()), - request.HistoryGroup, - cancellationToken).ConfigureAwait(false); + // 编排抽取不抽样:本轮的奖品顺序事先排定,抽取只是按序取奖。没有可用编排名单时静默回退随机抽奖, + // 与点名通道一致(主页面不暴露编排状态,缺名单不该让抽奖按钮变成死键)。 + var plan = configHandler.Data.EffectiveLotterySettings.DrawMode == DrawMode.Orchestrated + ? PrepareOrchestration(snapshot) + : null; + VerificationDrawOutcome? prizes; + if (plan is not null) + { + if (plan.Order.Count == 0) + return null; + prizes = await verification.DrawOrchestratedPrizesAsync( + plan.Order.Take(count).ToArray(), + plan.Round, + plan.RoundCount, + DrawProofExportContext.ForPrizes(GetPrizePoolName()), + cancellationToken).ConfigureAwait(false); + } + else + { + prizes = await verification.DrawPrizesAsync(count, + temporaryRecords.GetPrizeCounts(GetPrizePoolName()), snapshot.Prizes, + DrawProofExportContext.ForPrizes(GetPrizePoolName()), + request.HistoryGroup, + cancellationToken).ConfigureAwait(false); + } if (prizes is null) return null; IReadOnlyList assigned = []; VerificationDrawOutcome? assignedOutcome = null; if (hasStudentAssignment) { + // 抽奖轮里附带的「分配学生」是这一轮自己的随机分配:点名通道即使配了编排,也不能把点名排布 + // 塞进抽奖证明,所以这里显式按「无重复限制」抽样(候选集已在 GetSnapshot 里按点名设置过滤过)。 assignedOutcome = await verification.DrawStudentsAsync(count, snapshot.EligibleStudents, DrawSettingsType.RollCall, DrawProofExportContext.ForStudents(GetStudentListName(), request.Group, request.Gender, request.CourseName), - prizes.Proof.ProofId, request.CourseName, request.HistoryGroup, cancellationToken).ConfigureAwait(false); + prizes.Proof.ProofId, request.CourseName, request.HistoryGroup, cancellationToken, + configHandler.Data.EffectiveRollCallSettings.DrawMode == DrawMode.Orchestrated ? DrawMode.Repeat : null, + channel: "lottery") + .ConfigureAwait(false); if (assignedOutcome is null) return null; assigned = assignedOutcome.Winners; @@ -468,6 +635,12 @@ public void SwitchStudentList(string name) edit = edit with { Students = assigned, Prizes = prizes.Winners }; } + var recordGroup = HistoryRecordGroup.Resolve(historyGroupCatalog, logger, HistoryGroupKind.Lottery, + configHandler.Data.EffectiveLotterySettings.HistoryGroup, request.HistoryGroup); + // 抽奖附带抽中的学生在学生历史里另算一条通道:未按组筛选时落点名通道的默认记录组, + // 而不是奖池那一组的名字(两边是两份独立的历史文件,组名互不可见)。 + var studentRecordGroup = HistoryRecordGroup.Resolve(historyGroupCatalog, logger, HistoryGroupKind.RollCall, + configHandler.Data.EffectiveRollCallSettings.HistoryGroup, request.HistoryGroup); var roundId = edit?.SuppressHistory == true ? edit.OverrideRoundId ?? string.Empty : drawCommits.CommitLotteryDraw(new LotteryDrawCommit( @@ -483,11 +656,17 @@ public void SwitchStudentList(string name) (int)configHandler.Data.EffectiveRollCallSettings.DrawType, request.CourseName, edit?.OverrideRoundId, - request.HistoryGroup)); + request.HistoryGroup, + recordGroup, + studentRecordGroup)); PublishProof(prizes); if (assignedOutcome is not null) PublishProof(assignedOutcome); + // 一轮抽完(奖池被这次抽干,或剩无可抽)就推进到下一轮,并清掉本轮临时记录,否则下轮开局全员「已抽」。 + if (plan is not null && count >= snapshot.RemainingCount) + AdvanceOrchestration(plan); + usageReport.RecordLottery(); // 抽签完成事件:奖品与分配到的学生一起广播,插件不必自己拼历史。 eventBus?.Publish(new HostEvents.DrawCompleted( @@ -505,11 +684,70 @@ public void SwitchStudentList(string name) public void Reset(string studentListName, string group, string gender) { + // 编排里「重置」也算一轮:即使没抽完,也按用户的语义进入下一轮。 + if (configHandler.Data.EffectiveLotterySettings.DrawMode == DrawMode.Orchestrated + && orchestrationStore is not null) + { + var profile = orchestrationStore.FindActive(OrchestrationTarget.Lottery, GetPrizePoolName()).FirstOrDefault(); + if (profile is not null) + orchestrationStore.SaveRuntime(AdvanceRuntime(profile, orchestrationStore.GetRuntime(profile))); + } + temporaryRecords.ClearPrizeList(GetPrizePoolName()); if (!string.IsNullOrWhiteSpace(studentListName)) temporaryRecords.ClearStudentScope(GetStudentListName(), gender, group); } + private LotteryOrchestrationPlan? PrepareOrchestration(LotteryDrawSnapshot snapshot) + { + if (orchestrationStore is null || orchestrationScheduler is null) + return null; + var profile = orchestrationStore.FindActive(OrchestrationTarget.Lottery, GetPrizePoolName()).FirstOrDefault(); + if (profile is null) + return null; + + var runtime = orchestrationStore.GetRuntime(profile); + var drawn = new Dictionary(); + foreach (var entry in temporaryRecords.GetPrizeCounts(GetPrizePoolName())) + { + if (Guid.TryParseExact(entry.Key, "N", out var recordId)) + drawn[recordId] = entry.Value; + } + + var order = orchestrationScheduler.OrderRound( + profile, + profile.GetRound(runtime.Round), + snapshot.Remaining, + drawn, + randomSource ?? FallbackRandom); + return new LotteryOrchestrationPlan(profile, runtime.Round, profile.EffectiveRoundCount, order); + } + + private void AdvanceOrchestration(LotteryOrchestrationPlan plan) + { + if (orchestrationStore is null) + return; + + orchestrationStore.SaveRuntime(AdvanceRuntime(plan.Profile, orchestrationStore.GetRuntime(plan.Profile))); + // 下一轮整池重新可抽:不清掉本轮临时记录,下一轮开局就会人人被判为「已抽」。 + temporaryRecords.ClearPrizeList(GetPrizePoolName()); + } + + private static OrchestrationRuntime AdvanceRuntime(OrchestrationProfile profile, OrchestrationRuntime runtime) + { + runtime.Round = runtime.Round >= profile.EffectiveRoundCount ? 1 : runtime.Round + 1; + runtime.UpdatedAt = DateTime.UtcNow; + return runtime; + } + + private sealed record LotteryOrchestrationPlan( + OrchestrationProfile Profile, + int Round, + int RoundCount, + IReadOnlyList Order); + + private static readonly CryptoRandomSource FallbackRandom = new(); + /// Temporary-record scope for number prize draws; deliberately not a real prize-pool name. public const string NumberPrizePoolName = "__number_prize_pool__"; @@ -556,7 +794,8 @@ public LotteryNumberSnapshot GetNumberSnapshot(int rangeStart, int rangeEnd) { assignedOutcome = await verification.DrawStudentsAsync(count, eligible, DrawSettingsType.RollCall, DrawProofExportContext.ForStudents(GetStudentListName(), request.Group, request.Gender, request.CourseName), - prizes.Proof.ProofId, request.CourseName, request.HistoryGroup, cancellationToken).ConfigureAwait(false); + prizes.Proof.ProofId, request.CourseName, request.HistoryGroup, cancellationToken, + channel: "lottery").ConfigureAwait(false); if (assignedOutcome is null) return null; assigned = assignedOutcome.Winners; diff --git a/SecRandom/Views/SettingsPages/Picking/LotteryDrawSettingsPage.axaml b/SecRandom/Views/SettingsPages/Picking/LotteryDrawSettingsPage.axaml index c0c4cec42..5cc0183c2 100644 --- a/SecRandom/Views/SettingsPages/Picking/LotteryDrawSettingsPage.axaml +++ b/SecRandom/Views/SettingsPages/Picking/LotteryDrawSettingsPage.axaml @@ -22,7 +22,7 @@ Description="{x:Static lp:Resources.S_DrawMode_D}" IconSource="{sr:FluentIconSource {sr:Fi FlashFilled}}"> - + @@ -33,7 +33,7 @@ + IsVisible="{Binding Settings.SampledDrawMode, Converter={x:Static ObjectConverters.Equal}, ConverterParameter={x:Static enums:DrawMode.HalfRepeat}}"> @@ -65,23 +65,16 @@ + 选「默认记录组」表示只算未分组的记录;总开关关闭时整张卡隐藏。 --> - - - - + diff --git a/SecRandom/Views/SettingsPages/Picking/LotteryDrawSettingsPage.axaml.cs b/SecRandom/Views/SettingsPages/Picking/LotteryDrawSettingsPage.axaml.cs index 5ea9df226..ed4c00ad9 100644 --- a/SecRandom/Views/SettingsPages/Picking/LotteryDrawSettingsPage.axaml.cs +++ b/SecRandom/Views/SettingsPages/Picking/LotteryDrawSettingsPage.axaml.cs @@ -61,7 +61,13 @@ public LotteryDrawSettingsPage() public ObservableCollection DefaultPoolOptions => DefaultPoolSource.Options; public IReadOnlyList Algorithms { get; } = LotteryAlgorithmRegistryService.RegisteredAlgorithms - .Select(x => new LotteryAlgorithmOption(x.Id, x.Name)).ToArray(); + .Select(x => new LotteryAlgorithmOption(x.Id, x.Name)) + .Append(OrchestratedOption) + .ToArray(); + + /// 「编排抽取」不是注册的抽样算法,只是「抽取方式」里的第三个选项。 + private static readonly LotteryAlgorithmOption OrchestratedOption = + new(DrawModeCatalog.OrchestratedOptionId, PickingResources.O_Orchestrated); /// /// 抽奖页的默认记录组:页面打开时选择器先落到这里,用户当场换组仍然只改界面状态、不写配置。 @@ -71,12 +77,27 @@ public LotteryDrawSettingsPage() public LotteryAlgorithmOption? SelectedAlgorithm { - get => Algorithms.FirstOrDefault(x => string.Equals(x.Id, Settings.AlgorithmId, StringComparison.OrdinalIgnoreCase)) - ?? Algorithms.FirstOrDefault(); + get => DrawModeSelection.IsOrchestrated(Settings.DrawMode) + ? OrchestratedOption + : Algorithms.FirstOrDefault(x => string.Equals(x.Id, Settings.AlgorithmId, StringComparison.OrdinalIgnoreCase)) + ?? Algorithms.FirstOrDefault(); set { - if (value is null || string.Equals(Settings.AlgorithmId, value.Id, StringComparison.OrdinalIgnoreCase)) + if (value is null) return; + + if (string.Equals(value.Id, DrawModeCatalog.OrchestratedOptionId, StringComparison.OrdinalIgnoreCase)) + { + DrawModeSelection.SelectOrchestrated(Settings); + return; + } + + if (string.Equals(Settings.AlgorithmId, value.Id, StringComparison.OrdinalIgnoreCase) + && !DrawModeSelection.IsOrchestrated(Settings.DrawMode)) + return; + + // 改回抽样算法:先把进入编排前的重复策略还回去,否则抽取端还以为这个通道在编排。 + DrawModeSelection.LeaveOrchestrated(Settings); Settings.AlgorithmId = value.Id; if (string.Equals(value.Id, "builtin.inventory", StringComparison.OrdinalIgnoreCase)) Settings.DrawType = LotteryDrawType.Count; @@ -145,6 +166,8 @@ private void OnLoaded(object? sender, RoutedEventArgs e) { MusicLibrary.Refresh(); RefreshHistoryGroupSelection(); + ApplyDefaultPoolCardVisibility(); + ApplyHistoryGroupCardVisibility(); SubscribeSettings(); } @@ -165,6 +188,7 @@ private void HistoryGroupsOnPropertyChanged(object? sender, PropertyChangedEvent HistoryGroup.Refresh(); ApplyHistoryGroupSelection(); + ApplyHistoryGroupCardVisibility(); } private void SettingsOnPropertyChanged(object? sender, PropertyChangedEventArgs e) @@ -178,6 +202,14 @@ private void SettingsOnPropertyChanged(object? sender, PropertyChangedEventArgs if (e.PropertyName == nameof(LotterySettingsConfig.DefaultPool)) DefaultPoolSource.Sync(DefaultPoolSelector); + // 抽取方式换了(含进出编排):只有非编排时,记住的重复策略才跟着 DrawMode 走。 + if (e.PropertyName == nameof(LotterySettingsConfig.DrawMode)) + DrawModeSelection.SynchronizeRepeatPolicy(Settings); + + // 「抽取模式」下拉框绑的是 SampledDrawMode:非编排时它才是真正生效的重复策略。 + if (e.PropertyName == nameof(LotterySettingsConfig.SampledDrawMode)) + DrawModeSelection.SetRepeatPolicy(Settings, Settings.SampledDrawMode); + NormalizeDrawSettings(); ConfigHandler.Save(); } @@ -193,7 +225,12 @@ private void SubscribeSettings() } /// 重建默认奖池候选值,并把选中项落回配置(未配置过时落到第一份并写回)。 - private void RefreshPrizeLists() => DefaultPoolSource.Refresh(DefaultPoolSelector); + private void RefreshPrizeLists() + { + DefaultPoolSource.Refresh(DefaultPoolSelector); + ApplyDefaultPoolCardVisibility(); + ApplyHistoryGroupCardVisibility(); + } private void DefaultPoolSelectorOnSelectionChanged(object? sender, SelectionChangedEventArgs e) => DefaultPoolSource.OnSelectionChanged(sender, e); @@ -206,7 +243,14 @@ private void NormalizeDrawSettings() _normalizingSettings = true; try { - Settings.HalfRepeat = Settings.DrawMode switch + // 「抽取模式」下拉框绑的是 SampledDrawMode,每一项都必须是 0..2 的重复策略: + // 手改的配置、旧存档或控制面下发可能写成编排,三个选项的下拉框还会先把越界索引 + // 压成 -1 再经 TwoWay 写回,所以任何非重复策略都要修回当前应显示的那一档。 + var repeatPolicy = DrawModeSelection.ResolveRepeatPolicy(Settings); + Settings.SampledDrawMode = repeatPolicy; + + // 半重复档位按「抽取模式」下拉框显示的那一档来夹:编排期间显示的是记住的重复策略。 + Settings.HalfRepeat = repeatPolicy switch { DrawMode.Repeat => 0, DrawMode.NoRepeat => 1, @@ -239,6 +283,20 @@ private void InsertCustomLotteryShowRandomFormatTokenOnClick(object? sender, Rou textBox.SelectionEnd = caret; textBox.Focus(); } + + /// 奖池可以全部删除:没有奖池时这张默认奖池卡没有可选项,整卡隐藏。 + private void ApplyDefaultPoolCardVisibility() + { + if (this.FindControl("S_DefaultPool") is { } card) + card.IsVisible = DefaultPoolSource.HasRosters; + } + + /// 历史记录组总开关关闭时整卡隐藏:没有地方能解释一个不存在功能的选择器。 + private void ApplyHistoryGroupCardVisibility() + { + if (this.FindControl("S_LotteryHistoryGroup") is { } card) + card.IsVisible = HistoryGroups.Enabled; + } } public sealed record LotteryAlgorithmOption(string Id, string Name); diff --git a/SecRandom/Views/SettingsPages/Picking/OrchestrationEditingSession.cs b/SecRandom/Views/SettingsPages/Picking/OrchestrationEditingSession.cs new file mode 100644 index 000000000..78f3a5b52 --- /dev/null +++ b/SecRandom/Views/SettingsPages/Picking/OrchestrationEditingSession.cs @@ -0,0 +1,41 @@ +using SecRandom.Core.Models.Orchestration; + +namespace SecRandom.Views.SettingsPages.Picking; + +/// +/// Which arranged profile and which round the five list settings pages open on. +/// +/// +/// The overview page owns the profile picker; a list page is a hidden page reached only from that overview, so +/// it has no picker of its own and must not guess. Rather than a global "current profile" that could survive a +/// page reload and point at a deleted list, the overview states the selection right before navigating and each +/// list page re-reads the profile from IOrchestrationStore by that id — a stale object never edits. +/// +internal static class OrchestrationEditingSession +{ + public const string ExcludePage = "settings.picking.orchestration.exclude"; + public const string WeightPage = "settings.picking.orchestration.weight"; + public const string DeferPage = "settings.picking.orchestration.defer"; + public const string OrderPage = "settings.picking.orchestration.order"; + public const string GuaranteePage = "settings.picking.orchestration.guarantee"; + + public static string? ProfileId { get; private set; } + + public static int Round { get; private set; } = 1; + + public static void Open(string profileId, int round) + { + ProfileId = profileId; + Round = Math.Max(1, round); + } + + public static string PageIdOf(OrchestrationRuleKind kind) => kind switch + { + OrchestrationRuleKind.Exclude => ExcludePage, + OrchestrationRuleKind.Weight => WeightPage, + OrchestrationRuleKind.Defer => DeferPage, + OrchestrationRuleKind.Order => OrderPage, + OrchestrationRuleKind.Guarantee => GuaranteePage, + _ => ExcludePage + }; +} \ No newline at end of file diff --git a/SecRandom/Views/SettingsPages/Picking/OrchestrationEditorDrawer.axaml b/SecRandom/Views/SettingsPages/Picking/OrchestrationEditorDrawer.axaml new file mode 100644 index 000000000..8a1642423 --- /dev/null +++ b/SecRandom/Views/SettingsPages/Picking/OrchestrationEditorDrawer.axaml @@ -0,0 +1,76 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/SecRandom/Views/SettingsPages/Picking/OrchestrationRulePageBase.axaml.cs b/SecRandom/Views/SettingsPages/Picking/OrchestrationRulePageBase.axaml.cs new file mode 100644 index 000000000..a02f54293 --- /dev/null +++ b/SecRandom/Views/SettingsPages/Picking/OrchestrationRulePageBase.axaml.cs @@ -0,0 +1,688 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using Avalonia; +using Avalonia.Controls; +using Avalonia.Interactivity; +using FluentAvalonia.UI.Controls; +using SecRandom.Core.Abstraction; +using SecRandom.Core.Helpers.UI; +using SecRandom.Core.Icons; +using SecRandom.Core.Models.Orchestration; +using SecRandom.Core.Services.Orchestration; +using PR = SecRandom.Langs.SettingsPages.Picking.Resources; + +namespace SecRandom.Views.SettingsPages.Picking; + +/// +/// One of the five list settings pages: 排斥 / 权重 / 延后 / 顺序 / 必中. +/// +/// +/// +/// All five are the same screen with the same member rows, because the difference between them is a rule, +/// not a layout: what a check means (「不参加」「本轮先不抽」「进队列」「排最前」) and whether the row carries a +/// weight box or the queue's up/down controls. Splitting them into five pages is what stops one member's +/// five unrelated settings from sitting side by side in one grid, where flipping 顺序 and 必中 at once looked +/// like a valid state. +/// +/// +/// The page is hidden from the settings navigation and reached only from the arrangement overview +/// ( carries the profile and round). It re-reads the profile from +/// the store on every attach and saves immediately on each edit, because a draw reads the file. +/// +/// +public abstract partial class OrchestrationRulePageBase : UserControl, INotifyPropertyChanged +{ + private readonly IOrchestrationStore _store = IAppHost.GetService(); + private OrchestrationProfile? _profile; + private OrchestrationRound _round = new(); + private int _selectedRound = 1; + private string _searchText = string.Empty; + private event PropertyChangedEventHandler? NotifyPropertyChanged; + + protected OrchestrationRulePageBase(OrchestrationRuleKind kind) + { + Kind = kind; + DataContext = this; + InitializeComponent(); + Load(); + } + + public OrchestrationRuleKind Kind { get; } + + public ObservableCollection Rows { get; } = []; + + public ObservableCollection RoundOptions { get; } = []; + + public bool HasRows => Rows.Count > 0; + + public bool IsRoundScoped => Kind != OrchestrationRuleKind.Exclude; + + public bool IsExcludePage => Kind == OrchestrationRuleKind.Exclude; + + public bool IsWeightPage => Kind == OrchestrationRuleKind.Weight; + + public bool IsDeferPage => Kind == OrchestrationRuleKind.Defer; + + public bool IsOrderPage => Kind == OrchestrationRuleKind.Order; + + public bool IsGuaranteePage => Kind == OrchestrationRuleKind.Guarantee; + + public string HeaderGlyph => Kind switch + { + OrchestrationRuleKind.Exclude => FluentIcons.ProhibitedFilled, + OrchestrationRuleKind.Weight => FluentIcons.ScalesFilled, + OrchestrationRuleKind.Defer => FluentIcons.TimerFilled, + OrchestrationRuleKind.Order => FluentIcons.ArrowSortFilled, + _ => FluentIcons.TargetFilled + }; + + public string PageTitle => Kind switch + { + OrchestrationRuleKind.Exclude => PR.S_Orchestration_Exclude, + OrchestrationRuleKind.Weight => PR.S_Orchestration_Weight, + OrchestrationRuleKind.Defer => PR.S_Orchestration_Defer, + OrchestrationRuleKind.Order => PR.S_Orchestration_Order, + _ => PR.S_Orchestration_Guarantee + }; + + public string RuleHint => Kind switch + { + OrchestrationRuleKind.Exclude => PR.C_Rule_ExcludeHint_D, + OrchestrationRuleKind.Weight => PR.C_Rule_WeightHint_D, + OrchestrationRuleKind.Defer => PR.C_Rule_DeferHint_D, + OrchestrationRuleKind.Order => PR.C_Rule_OrderHint_D, + _ => PR.C_Rule_GuaranteeHint_D + }; + + public string HeaderDetail + { + get + { + if (_profile is null) + return PR.C_Rule_NoProfile; + + var target = _profile.Target == OrchestrationTarget.Lottery + ? PR.O_Orchestration_TargetLottery + : PR.O_Orchestration_TargetRollCall; + return string.Format(PR.C_Rule_Profile, _profile.Name, target, _profile.SourceListName); + } + } + + /// 这份名单开关没开时,内容仍然可以编辑,但抽取端不会用它。 + public bool IsRuleDisabled => _profile is not null && !_profile.Rules.IsEnabled(Kind); + + public bool CanEdit => _profile is not null && SettingsView.Current?.IsPreviewMode != true; + + public string CountText => _profile is null + ? string.Empty + : string.Format(PR.S_Rule_Count, _profile.Members.Count, CountInList()); + + public string EmptyState + { + get + { + if (_profile is null) + return PR.C_Rule_NoProfile_D; + if (_profile.Members.Count == 0) + return PR.C_Rule_NoMembers_D; + return PR.C_Rule_NoMatch_D; + } + } + + public string SearchText + { + get => _searchText; + set + { + _searchText = value ?? string.Empty; + OnPropertyChanged(); + RebuildRows(); + } + } + + public int SelectedRound + { + get => _selectedRound; + set + { + var clamped = Math.Max(1, value); + if (_selectedRound == clamped) + return; + _selectedRound = clamped; + OnPropertyChanged(); + SelectRound(); + } + } + + event PropertyChangedEventHandler? INotifyPropertyChanged.PropertyChanged + { + add => NotifyPropertyChanged += value; + remove => NotifyPropertyChanged -= value; + } + + private void OnAttachedToVisualTree(object? sender, VisualTreeAttachmentEventArgs e) => Load(); + + /// + /// Re-reads the arranged profile the overview handed over. A missing profile (deleted, or the page opened + /// directly) is not an error: the page shows "choose a list first" instead of editing nothing. + /// + private void Load() + { + _profile = OrchestrationEditingSession.ProfileId is { } id ? _store.Load(id) : null; + _selectedRound = _profile is null + ? 1 + : Math.Clamp(OrchestrationEditingSession.Round, 1, _profile.EffectiveRoundCount); + RefreshRoundOptions(); + SelectRound(); + } + + private void SelectRound() + { + Rows.Clear(); + if (_profile is not null) + { + _round = _profile.GetRound(_selectedRound); + RebuildRows(); + } + + NotifyAll(); + } + + private void RefreshRoundOptions() + { + RoundOptions.Clear(); + if (_profile is null) + return; + for (var index = 1; index <= _profile.EffectiveRoundCount; index++) + RoundOptions.Add(index); + } + + /// + /// Builds the visible rows. 顺序 and 必中 are ordered lists, so whoever is on the list comes first in list + /// order and everyone else follows as "not on this list yet"; the other lists keep the member order. + /// + private void RebuildRows() + { + Rows.Clear(); + if (_profile is null) + return; + + var members = _profile.Members + .Where(member => Matches(member)) + .ToList(); + + if (Kind is OrchestrationRuleKind.Order or OrchestrationRuleKind.Guarantee) + { + var list = Kind == OrchestrationRuleKind.Order ? _round.Order : _round.Guaranteed; + var ordered = new List(); + foreach (var recordId in list) + { + var member = members.FirstOrDefault(candidate => candidate.RecordId == recordId); + if (member is not null) + ordered.Add(member); + } + + ordered.AddRange(members.Where(member => !list.Contains(member.RecordId))); + members = ordered; + } + + for (var index = 0; index < members.Count; index++) + { + var row = new OrchestrationRuleMemberRow(Kind, _profile, _round, members[index], OnRowChanged); + row.SetPosition(ResolvePosition(row.Member.RecordId), CanMove(row, -1), CanMove(row, 1)); + Rows.Add(row); + } + + OnPropertyChanged(nameof(HasRows)); + } + + private bool Matches(OrchestrationMember member) + { + if (string.IsNullOrWhiteSpace(_searchText)) + return true; + return member.Number.Contains(_searchText, StringComparison.CurrentCultureIgnoreCase) + || member.Name.Contains(_searchText, StringComparison.CurrentCultureIgnoreCase); + } + + private int ResolvePosition(Guid recordId) + { + var list = Kind == OrchestrationRuleKind.Order ? _round.Order : _round.Guaranteed; + if (Kind is not (OrchestrationRuleKind.Order or OrchestrationRuleKind.Guarantee)) + return 0; + var index = list.IndexOf(recordId); + return index < 0 ? 0 : index + 1; + } + + private bool CanMove(OrchestrationRuleMemberRow row, int delta) + { + if (Kind is not (OrchestrationRuleKind.Order or OrchestrationRuleKind.Guarantee)) + return false; + var list = Kind == OrchestrationRuleKind.Order ? _round.Order : _round.Guaranteed; + var index = list.IndexOf(row.Member.RecordId); + if (index < 0) + return delta > 0; // 还没进名单的人可以「往上」加入;已在名单里的才谈得上移动 + var target = index + delta; + return target >= 0 && target < list.Count; + } + + private int CountInList() => Kind switch + { + OrchestrationRuleKind.Exclude => _profile?.Members.Count(member => member.IsExcluded) ?? 0, + OrchestrationRuleKind.Weight => _round.Weights.Count, + OrchestrationRuleKind.Defer => _round.Skipped.Count, + OrchestrationRuleKind.Order => _round.Order.Count, + _ => _round.Guaranteed.Count + }; + + private void OnRowChanged() + { + Save(); + RebuildRows(); + NotifyAll(); + } + + private void Save() + { + if (_profile is not null) + _store.Save(_profile); + } + + /// + /// 勾选/取消勾选一名成员。取消勾选不会冲突,直接生效;勾选前先问一句「这会取消哪份名单」, + /// 因为这份名单和别的名单互斥的地方都在模型里(排斥清全局、延后清顺序与必中、顺序清必中……), + /// 让用户看着自己按下的这一下会撤掉什么,而不是保存完才发现另一页空了。 + /// + private async void Toggle_OnClick(object? sender, RoutedEventArgs e) + { + if (sender is not CheckBox box || box.DataContext is not OrchestrationRuleMemberRow row) + return; + + var wanted = box.IsChecked == true; + if (wanted && _profile is not null) + { + var cancelled = DescribeCancelledLists(row.Member.RecordId); + if (cancelled.Count > 0 && !await ConfirmCancelAsync(cancelled)) + { + // 绑定是 OneWay,用户点出来的一下要自己退回去,否则界面会说谎。 + box.IsChecked = row.IsInList; + return; + } + } + + row.IsInList = wanted; + } + + /// 勾上这一行会顺手取消的其他名单,空表示没有互斥冲突,不该打扰用户。 + private List DescribeCancelledLists(Guid recordId) + { + var cancelled = new List(); + if (_profile is null) + return cancelled; + + switch (Kind) + { + case OrchestrationRuleKind.Exclude: + // 排斥是全局的:每一轮的顺序、延后、必中、权重都会随这一勾消失。 + foreach (var round in _profile.Rounds) + CollectConflicts(cancelled, round, recordId, defer: true, order: true, guarantee: true, weight: true); + break; + + case OrchestrationRuleKind.Defer: + if (_profile.FindMember(recordId)?.IsExcluded == true) + cancelled.Add(PR.S_Orchestration_Exclude); + CollectConflicts(cancelled, _round, recordId, defer: false, order: true, guarantee: true, weight: false); + break; + + case OrchestrationRuleKind.Order: + CollectConflicts(cancelled, _round, recordId, defer: false, order: false, guarantee: true, weight: false); + break; + + case OrchestrationRuleKind.Guarantee: + CollectConflicts(cancelled, _round, recordId, defer: true, order: true, guarantee: false, weight: false); + break; + } + + return cancelled; + } + + private static void CollectConflicts( + List target, + OrchestrationRound round, + Guid recordId, + bool defer, + bool order, + bool guarantee, + bool weight) + { + if (defer && round.Skipped.Contains(recordId)) + target.Add(string.Format(PR.M_Rule_ConflictRound, round.Index, PR.S_Orchestration_Defer)); + if (order && round.Order.Contains(recordId)) + target.Add(string.Format(PR.M_Rule_ConflictRound, round.Index, PR.S_Orchestration_Order)); + if (guarantee && round.Guaranteed.Contains(recordId)) + target.Add(string.Format(PR.M_Rule_ConflictRound, round.Index, PR.S_Orchestration_Guarantee)); + if (weight && round.Weights.ContainsKey(recordId)) + target.Add(string.Format(PR.M_Rule_ConflictRound, round.Index, PR.S_Orchestration_Weight)); + } + + private async Task ConfirmCancelAsync(IReadOnlyList cancelled) + { + var result = await new FAContentDialog + { + Title = PR.M_Rule_ConflictTitle, + Content = string.Format(PR.M_Rule_ConflictContent, PageTitle, string.Join(PR.C_Rule_ConflictJoin, cancelled)), + PrimaryButtonText = PR.C_Rule_Continue, + CloseButtonText = PR.C_Orchestration_Cancel, + DefaultButton = FAContentDialogButton.Close + }.ShowAsync(TopLevel.GetTopLevel(this)); + return result == FAContentDialogResult.Primary; + } + + private async Task MoveAsync(OrchestrationRuleMemberRow row, int delta) + { + if (_profile is null) + return; + + var list = Kind == OrchestrationRuleKind.Order ? _round.Order : _round.Guaranteed; + var recordId = row.Member.RecordId; + var index = list.IndexOf(recordId); + if (index < 0) + { + // 不在名单里的人:往上按一下等于排到队尾,和勾选一样要过互斥确认。 + if (delta <= 0) + return; + + var cancelled = DescribeCancelledLists(recordId); + if (cancelled.Count > 0 && !await ConfirmCancelAsync(cancelled)) + return; + + list.Add(recordId); + } + else + { + var target = index + delta; + if (target < 0 || target >= list.Count) + return; + (list[index], list[target]) = (list[target], list[index]); + } + + // 顺序名单的队列要按成员集合过滤一遍:直接改 List 会绕过 SetOrder 的去重与必中互斥。 + if (Kind == OrchestrationRuleKind.Order) + _profile.SetOrder(_round, list); + Save(); + RebuildRows(); + NotifyAll(); + } + + private async void MoveUpButton_OnClick(object? sender, RoutedEventArgs e) + { + if (sender is Button { CommandParameter: OrchestrationRuleMemberRow row }) + await MoveAsync(row, -1); + } + + private async void MoveDownButton_OnClick(object? sender, RoutedEventArgs e) + { + if (sender is Button { CommandParameter: OrchestrationRuleMemberRow row }) + await MoveAsync(row, 1); + } + + /// 只对顺序名单有意义:本轮参与者的队列随机重排。必中名单的顺序由权重和加入次序决定。 + private async void ShuffleButton_OnClick(object? sender, RoutedEventArgs e) + { + if (_profile is null || Kind != OrchestrationRuleKind.Order) + return; + + if (_round.Guaranteed.Count > 0 && !await ConfirmReplaceAsync(PR.M_Rule_ShuffleConflict)) + return; + + var ids = _profile.Members + .Where(member => !member.IsExcluded && !_round.Skipped.Contains(member.RecordId)) + .Select(member => member.RecordId) + .ToArray(); + for (var index = ids.Length - 1; index > 0; index--) + { + var swap = Random.Shared.Next(index + 1); + (ids[index], ids[swap]) = (ids[swap], ids[index]); + } + + _profile.SetOrder(_round, ids); + Save(); + RebuildRows(); + NotifyAll(); + this.ShowSuccessToast(PR.M_Rule_Shuffled); + } + + private async void CopyOrderButton_OnClick(object? sender, RoutedEventArgs e) + { + if (_profile is null || Kind != OrchestrationRuleKind.Order || _round.Order.Count == 0) + return; + + var otherRounds = Enumerable + .Range(1, _profile.EffectiveRoundCount) + .Where(index => index != _selectedRound) + .Select(_profile.GetRound) + .ToArray(); + if (otherRounds.Any(round => round.Guaranteed.Count > 0) + && !await ConfirmReplaceAsync(PR.M_Rule_CopyConflict)) + return; + + var sequence = _round.Order.ToList(); + foreach (var round in otherRounds) + _profile.SetOrder(round, sequence); + + Save(); + this.ShowSuccessToast(string.Format(PR.M_Rule_OrderCopied, otherRounds.Length)); + } + + private async Task ConfirmReplaceAsync(string content) + { + var result = await new FAContentDialog + { + Title = PR.M_Rule_ConflictTitle, + Content = content, + PrimaryButtonText = PR.C_Rule_ReplaceOrder, + CloseButtonText = PR.C_Orchestration_Cancel, + DefaultButton = FAContentDialogButton.Close + }.ShowAsync(TopLevel.GetTopLevel(this)); + return result == FAContentDialogResult.Primary; + } + + /// 清空当前这一份名单——不动其他四份,也不动成员本身。 + private void ClearListButton_OnClick(object? sender, RoutedEventArgs e) + { + if (_profile is null) + return; + + switch (Kind) + { + case OrchestrationRuleKind.Exclude: + foreach (var member in _profile.Members) + member.IsExcluded = false; + break; + case OrchestrationRuleKind.Weight: + _round.Weights.Clear(); + break; + case OrchestrationRuleKind.Defer: + _round.Skipped.Clear(); + break; + case OrchestrationRuleKind.Order: + _profile.SetOrder(_round, []); + break; + case OrchestrationRuleKind.Guarantee: + _round.Guaranteed.Clear(); + break; + } + + Save(); + RebuildRows(); + NotifyAll(); + this.ShowSuccessToast(string.Format(PR.M_Rule_Cleared, PageTitle)); + } + + private void NotifyAll() + { + OnPropertyChanged(nameof(HasRows)); + OnPropertyChanged(nameof(CountText)); + OnPropertyChanged(nameof(IsRuleDisabled)); + OnPropertyChanged(nameof(CanEdit)); + OnPropertyChanged(nameof(HeaderDetail)); + OnPropertyChanged(nameof(EmptyState)); + } + + private void OnPropertyChanged([CallerMemberName] string? propertyName = null) => + NotifyPropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); +} + +/// +/// One member on one of the five list pages. The row mutates the model directly (the page then saves and rebuilds), +/// so the same member can be looked at from five angles without any of them writing another list's data. +/// +public sealed class OrchestrationRuleMemberRow : INotifyPropertyChanged +{ + private readonly OrchestrationProfile _profile; + private readonly OrchestrationRound _round; + private readonly Action _changed; + private int _position; + private bool _canMoveUp; + private bool _canMoveDown; + private event PropertyChangedEventHandler? NotifyPropertyChanged; + + public OrchestrationRuleMemberRow( + OrchestrationRuleKind kind, + OrchestrationProfile profile, + OrchestrationRound round, + OrchestrationMember member, + Action changed) + { + Kind = kind; + _profile = profile; + _round = round; + Member = member; + _changed = changed; + } + + public OrchestrationRuleKind Kind { get; } + + public OrchestrationMember Member { get; } + + public string DisplayName => $"{Member.Number} {Member.Name}".Trim(); + + public bool ShowPosition => Kind is OrchestrationRuleKind.Order or OrchestrationRuleKind.Guarantee; + + public bool ShowToggle => Kind != OrchestrationRuleKind.Weight; + + public bool ShowWeight => Kind == OrchestrationRuleKind.Weight; + + public bool ShowOrderButtons => Kind is OrchestrationRuleKind.Order or OrchestrationRuleKind.Guarantee; + + public string PositionText => _position > 0 ? _position.ToString() : "—"; + + public bool CanMoveUp => _canMoveUp; + + public bool CanMoveDown => _canMoveDown; + + public void SetPosition(int position, bool canMoveUp, bool canMoveDown) + { + _position = position; + _canMoveUp = canMoveUp; + _canMoveDown = canMoveDown; + OnPropertyChanged(nameof(PositionText)); + OnPropertyChanged(nameof(CanMoveUp)); + OnPropertyChanged(nameof(CanMoveDown)); + } + + public string ToggleHint => Kind switch + { + OrchestrationRuleKind.Exclude => PR.C_Rule_ToggleExclude, + OrchestrationRuleKind.Defer => PR.C_Rule_ToggleDefer, + OrchestrationRuleKind.Order => PR.C_Rule_ToggleOrder, + _ => PR.C_Rule_ToggleGuarantee + }; + + /// Whether this member is currently on this page's list. + public bool IsInList + { + get => Kind switch + { + OrchestrationRuleKind.Exclude => Member.IsExcluded, + OrchestrationRuleKind.Defer => _round.Skipped.Contains(Member.RecordId), + OrchestrationRuleKind.Order => _round.Order.Contains(Member.RecordId), + OrchestrationRuleKind.Guarantee => _round.Guaranteed.Contains(Member.RecordId), + _ => false + }; + set + { + if (IsInList == value) + return; + + switch (Kind) + { + case OrchestrationRuleKind.Exclude: + _profile.SetExcluded(Member.RecordId, value); + break; + case OrchestrationRuleKind.Defer: + _profile.SetSkipped(_round, Member.RecordId, value); + break; + case OrchestrationRuleKind.Order: + // 走 SetOrder 而不是直接改 List:队列写入同时负责去重,并把队列里的人从必中名单里拿出来。 + _profile.SetOrder( + _round, + value + ? _round.Order.Concat([Member.RecordId]).ToList() + : _round.Order.Where(id => id != Member.RecordId).ToList()); + break; + case OrchestrationRuleKind.Guarantee: + _profile.SetGuaranteed(_round, Member.RecordId, value); + break; + } + + _changed(); + } + } + + public string WeightText + { + get => _round.Weights.TryGetValue(Member.RecordId, out var weight) ? weight.ToString("0.##") : string.Empty; + set + { + var parsed = double.TryParse(value, out var weight) && weight >= 0; + var current = _round.Weights.ContainsKey(Member.RecordId); + if (parsed is false && current is false) + return; + + _profile.SetWeight(_round, Member.RecordId, parsed ? Math.Clamp(weight, 0d, 100d) : null); + _changed(); + } + } + + public string Note + { + get + { + if (Member.IsSourceMissing) + return PR.C_Orchestration_SourceMissing; + if (Kind != OrchestrationRuleKind.Exclude && Member.IsExcluded) + return PR.C_Rule_ExcludeNote; + if (Kind == OrchestrationRuleKind.Order && !_round.Order.Contains(Member.RecordId)) + return PR.C_Rule_NotInQueue; + if (Kind == OrchestrationRuleKind.Guarantee && !_round.Guaranteed.Contains(Member.RecordId)) + return PR.C_Rule_NotGuaranteed; + return string.Empty; + } + } + + public bool HasNote => Note.Length > 0; + + event PropertyChangedEventHandler? INotifyPropertyChanged.PropertyChanged + { + add => NotifyPropertyChanged += value; + remove => NotifyPropertyChanged -= value; + } + + private void OnPropertyChanged([CallerMemberName] string? propertyName = null) => + NotifyPropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); +} \ No newline at end of file diff --git a/SecRandom/Views/SettingsPages/Picking/OrchestrationRulePages.cs b/SecRandom/Views/SettingsPages/Picking/OrchestrationRulePages.cs new file mode 100644 index 000000000..f3899fc7c --- /dev/null +++ b/SecRandom/Views/SettingsPages/Picking/OrchestrationRulePages.cs @@ -0,0 +1,55 @@ +using SecRandom.Core.Attributes; +using SecRandom.Core.Icons; +using SecRandom.Core.Models.Orchestration; + +namespace SecRandom.Views.SettingsPages.Picking; + +/// 排斥名单:全局不参加,抽取前就被拿掉。 +[PageInfo(OrchestrationEditingSession.ExcludePage, FluentIcons.ProhibitedFilled, "settings.picking", isHide: true)] +public sealed class OrchestrationExcludeSettingsPage : OrchestrationRulePageBase +{ + public OrchestrationExcludeSettingsPage() : base(OrchestrationRuleKind.Exclude) + { + // 页面不出现在侧栏:由编排抽取总览的「排斥名单」设置卡跳转进来。 + } +} + +/// 权重名单:轮级手动权重,作为公平权重的乘数。 +[PageInfo(OrchestrationEditingSession.WeightPage, FluentIcons.ScalesFilled, "settings.picking", isHide: true)] +public sealed class OrchestrationWeightSettingsPage : OrchestrationRulePageBase +{ + public OrchestrationWeightSettingsPage() : base(OrchestrationRuleKind.Weight) + { + // 页面不出现在侧栏:由编排抽取总览的「权重名单」设置卡跳转进来。 + } +} + +/// 延后名单:只把名字挪到本轮队尾,不取消参与资格。 +[PageInfo(OrchestrationEditingSession.DeferPage, FluentIcons.TimerFilled, "settings.picking", isHide: true)] +public sealed class OrchestrationDeferSettingsPage : OrchestrationRulePageBase +{ + public OrchestrationDeferSettingsPage() : base(OrchestrationRuleKind.Defer) + { + // 页面不出现在侧栏:由编排抽取总览的「延后名单」设置卡跳转进来。 + } +} + +/// 顺序名单:本轮出场队列,前面的先抽、抽完就离队。 +[PageInfo(OrchestrationEditingSession.OrderPage, FluentIcons.ArrowSortFilled, "settings.picking", isHide: true)] +public sealed class OrchestrationOrderSettingsPage : OrchestrationRulePageBase +{ + public OrchestrationOrderSettingsPage() : base(OrchestrationRuleKind.Order) + { + // 页面不出现在侧栏:由编排抽取总览的「顺序名单」设置卡跳转进来。 + } +} + +/// 必中名单:本轮必定出场的人,与顺序名单互斥。 +[PageInfo(OrchestrationEditingSession.GuaranteePage, FluentIcons.TargetFilled, "settings.picking", isHide: true)] +public sealed class OrchestrationGuaranteeSettingsPage : OrchestrationRulePageBase +{ + public OrchestrationGuaranteeSettingsPage() : base(OrchestrationRuleKind.Guarantee) + { + // 页面不出现在侧栏:由编排抽取总览的「必中名单」设置卡跳转进来。 + } +} \ No newline at end of file diff --git a/SecRandom/Views/SettingsPages/Picking/OrchestrationSettingsPage.axaml b/SecRandom/Views/SettingsPages/Picking/OrchestrationSettingsPage.axaml new file mode 100644 index 000000000..12e554043 --- /dev/null +++ b/SecRandom/Views/SettingsPages/Picking/OrchestrationSettingsPage.axaml @@ -0,0 +1,333 @@ + + + + + + + + + + + +