diff --git a/.github/workflows/build_ios.yml b/.github/workflows/build_ios.yml index d0539e474..51813a8c6 100644 --- a/.github/workflows/build_ios.yml +++ b/.github/workflows/build_ios.yml @@ -25,6 +25,9 @@ on: permissions: contents: read +env: + SECRANDOM_INTEGRATION_PUBLIC_KEY_SPKI_BASE64: ${{ vars.SECRANDOM_INTEGRATION_PUBLIC_KEY_SPKI_BASE64 }} + jobs: build_ios: name: Build_iOS diff --git a/.github/workflows/build_publish.yml b/.github/workflows/build_publish.yml index 3ee1449a7..7258930d1 100644 --- a/.github/workflows/build_publish.yml +++ b/.github/workflows/build_publish.yml @@ -14,6 +14,9 @@ on: permissions: contents: read +env: + SECRANDOM_INTEGRATION_PUBLIC_KEY_SPKI_BASE64: ${{ vars.SECRANDOM_INTEGRATION_PUBLIC_KEY_SPKI_BASE64 }} + jobs: # Release publication is gated on metadata.yaml: clients resolve a channel to a release tag there # and reject the release manifest when its tag/channel disagree, so a stale channel entry diff --git a/.github/workflows/codeQL.yml b/.github/workflows/codeQL.yml index 40a107950..73a82f3b0 100644 --- a/.github/workflows/codeQL.yml +++ b/.github/workflows/codeQL.yml @@ -6,6 +6,9 @@ on: schedule: - cron: "0 3 * * 1" +env: + SECRANDOM_INTEGRATION_PUBLIC_KEY_SPKI_BASE64: ${{ vars.SECRANDOM_INTEGRATION_PUBLIC_KEY_SPKI_BASE64 }} + jobs: analyze: name: CodeQL 分析 diff --git a/AGENTS.md b/AGENTS.md index eec8c4e9b..7043b98bb 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -15,7 +15,7 @@ Maintenance contract: - `docs/project_rules.md` is the source of truth when a convention conflicts with this summary. --> -**Last Update:** 2026-11-01 +**Last Update:** 2026-11-21 **Last Submit:** 51f7f7fd **Last modified model:** MiMoCode @@ -75,14 +75,16 @@ Nested instruction files: | Settings navigation | `SecRandom/Views/SettingsView.axaml.cs` | Default page `settings.overview`; has back stack + restart dialog. General group now includes `settings.general.basic`, `settings.general.privacy`, `settings.general.backup`, and `settings.general.control`. | | Page registration helpers | `SecRandom.Core/Extensions/Registry/` | `AddMainPage`, `AddSettingsPage`, group, and separator helpers. | | ClassIsland notifications | `SecRandom/Services/Notification/`, `SecRandom4Ci.Interface/` | Typed v2 IPC client for the installed SecRandom4Ci ClassIsland plugin. | -| Control-plane node (集控) | `docs/client-protocol.md`, `SecRandom.Core/Services/ControlNode/`, `SecRandom/Services/ControlNode/`, `SecRandom/Views/SettingsPages/General/ControlSettingsPage.axaml(.cs)` | v4.1 集控节点:WebSocket 打 `wss://sectl.cn/control/ws`(凭据放首帧 `hello.payload`,不在 URL/请求头),三分信封 `req`/`res`/`evt`;命令是 `evt cmd` + 两帧回执 `req cmd.ack`/`req cmd.result`(`id` 回填 `command_id`),`expires_at` 为 Unix 毫秒、过期即丢且不补投;期望状态 `evt desired_state` 带单调 `revision` 与 `draw_locked`(缺失按 true),客户端只接受严格更新的 revision 并把 `applied_state_revision` 落盘;接入是双因子「地点ID + 配对码」(`POST /control/api/enroll`),之后 `POST /control/api/device/tree` 拉年级/班级、`POST /control/api/device/assign` 保存,握手成功后用 `class.select`/`class.release` 占班(占班=上课=允许抽取);本地开关 `RemoteControlEnabled`(默认关)仍是最终否决权。协议规范、命令表与错误码以 `../SECTL-auth/docs/control-center-protocol-v4.md` 为唯一事实源;v1 的 `srn_` 令牌 / `group_id` / 单码接入已断代。 | +| Official SDK integration | `SecRandom/Services/Integration/`, `SecRandom/Views/SettingsPages/Linkage/`, `../SecRandom-Integration-SDK/docs/integration-v1.md` | Local signed-SDK discovery, user-approved result channels, and floating-window linkage leases; verification requires the compiled ECDSA public key and a matching live IPC peer process. | +| Control-plane node (集控) | `docs/client-protocol.md`, `SecRandom.Core/Services/ControlNode/`, `SecRandom/Services/ControlNode/`, `SecRandom/Views/SettingsPages/General/ControlSettingsPage.axaml(.cs)` | v4.1 集控节点:WebSocket 打 `wss://sectl.cn/control/ws`(凭据放首帧 `hello.payload`,不在 URL/请求头),三分信封 `req`/`res`/`evt`;命令是 `evt cmd` + 两帧回执 `req cmd.ack`/`req cmd.result`(`id` 回填 `command_id`),`expires_at` 为 Unix 毫秒、过期即丢且不补投;期望状态 `evt desired_state` 带单调 `revision` 与 `draw_locked`(缺失按 true),客户端只接受严格更新的 revision 并把 `applied_state_revision` 落盘;桌面被控节点有两条接入通道:双因子「地点ID + 配对码」(`POST /control/api/enroll`),或登录 SECTL 账号(`POST /control/api/device/enroll`,JWT + `device.enroll`;首次 operator、同机接管需 admin),两者写同一条接入记录;之后 `POST /control/api/device/tree` 拉年级/班级、`POST /control/api/device/assign` 保存,握手成功后用 `class.select`/`class.release` 占班(占班=上课=允许抽取);本地开关 `RemoteControlEnabled`(默认关)仍是最终否决权。平板与手机是纯账号控制台(`ControlCenterClient` 固定 `https://sectl.cn/control/api`,无配对码入口、无集控设置页),远程抽取页按 地点→年级→班级→该班 `occupancy["secrandom"]` 的在线占班设备下发 `draw.trigger`/`draw.reset`,结果只读回执 `payload.drawn`;点名/抽奖与名单下拉由只回名称的 `roster.list`(operator,v4.5)填充,设备不支持时回落默认名单。协议规范、命令表与错误码以 `../SECTL-auth/docs/control-center-protocol-v4.md` 为唯一事实源;v1 的 `srn_` 令牌 / `group_id` / 单码接入已断代。 | | Crash recovery | `SecRandom/Services/CrashRecovery/`, `SecRandom/Views/CrashRecoveryWindow.axaml.cs` | Fatal/dispatcher crash report prompt, guarded auto-restart, and shared desktop relaunch logic. | | Page registry state | `SecRandom.Core/Services/PagesRegistryService.cs` | Main/settings/group collections. | | Cross-platform view engine | `SecRandom.Core/Views/` | Logical view/session contracts; desktop and mobile shells provide DI-registered physical hosts. | | 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. | +| Orchestrated draw (编排抽取) | `SecRandom.Core/Models/Orchestration/OrchestrationModels.cs`, `SecRandom.Core/Services/Orchestration/` (`OrchestrationOrdering`, `OrchestrationScheduler`, `OrchestrationStore`, `OrchestrationVerification`), `SecRandom.Core/Services/Draw/DrawModeSelection.cs`, `SecRandom/Views/SettingsPages/Picking/OrchestrationSettingsPage.axaml(.cs)`, `OrchestrationRulePageBase.axaml(.cs)`, `OrchestrationRulePages.cs`, `OrchestrationEditingSession.cs`, `SecRandom/Services/Draw/SharedDrawServices.cs`, `docs/orchestrated-draw.md` | `DrawMode.Orchestrated` is neither a page nor a repeat policy: the order is decided *before* the draw, so a round is "take the next participant" instead of sampling. It is therefore the third choice of each channel's 「抽取方式」 dropdown (随机抽取 / 公平抽取 / 编排抽取, id `DrawModeCatalog.OrchestratedOptionId = "builtin.orchestrated"`, deliberately not a registered sampling algorithm) and is gone from the 「抽取模式」 repeat dropdown. Selecting it still persists `DrawMode.Orchestrated`, because the draw side reads only that; `DrawModeSelection.SelectOrchestrated` first records the channel's previous repeat policy in `OverridableDrawSettings.SampledDrawMode`, and `LeaveOrchestrated` restores it when the user picks a sampling method again — without that, one spell of orchestration would silently flatten a 半重复 setting to 不重复. While orchestrated the channel pages keep the 抽取模式 card visible — its three-item dropdown is bound to `SampledDrawMode` (the remembered repeat policy, always a valid 0..2 index) rather than to the four-valued `DrawMode`, so picking 编排抽取 can never push `SelectedIndex` to an out-of-range 3 and blank the selection — and hide only the 公平抽取策略 card; `S_DrawMode`/`S_FairDrawMode` keep their x:Names for settings search. An 编排名单 is its own entity (`OrchestrationProfile`, `data/config/orchestration/{id}.json`, runtime in `runtime/{id}.json`, both atomic replaces, `FormatVersion = 2`) bound to one `(target, source list)` pair, keyed by roster `RecordId`; only one list per pair is active, and a missing source record is flagged `IsSourceMissing` instead of deleted. The profile is edited as **five separate lists**, not one mixed grid: 「排斥」is global (`OrchestrationMember.IsExcluded`), while 「权重」/「延后」/「顺序」/「必中」 are per round (`OrchestrationRound.Weights`/`Skipped`/`Order`/`Guaranteed`, sparse, up to 10 rounds). `OrchestrationProfile.Rules` holds one switch per list and is the only place the lists can be muted: a list switched off keeps its data but stops participating, and 「顺序」and 「必中」are **mutually exclusive switches** (`SetEnabled` turns the other off) because both answer "who goes first" — with both populated in a hand-edited file, 必中 wins and the queue only seats the remainder, so nobody is seated twice. Ordering is a **queue**, not a set of absolute slots: `OrchestrationOrdering.Resolve` drops excluded/deferred/already-drawn members, puts the guaranteed group (internally by effective weight, stable) or else the round queue in front, then fills the rest by weighted sampling without replacement (`DrawEngine.CalculateStudentWeight`, manual weight is a multiplier clamped 0–100 that never changes the zero set) and finally the zero-weight tail by draw count descending, so nobody is ever dropped from a round. Because every draw re-resolves with the round's already-drawn members, a member queued third really comes out third after the first two leave, instead of being re-seated third inside the shrinking remainder. The old absolute-position `Pins` list survives only as a migration input: `OrchestrationStore.Normalize` (called on load and save) folds its positions into `Order` in pin order and then drops the field; it also clamps `RoundCount`, fills missing lists, and filters ids whose member is gone. The settings page is an **overview**, not an editor: command bar (当前名单 drawer / 新建 / 同步 / 名单设置 / 启用·停用), round row, channel-status strip, five `FASettingsExpander` cards that only carry a one-line summary each plus a 设置 button, and a separate `FASettingsExpander` of five `ToggleSwitch` rows for the rule switches. Each card jumps to its own **hidden** sub-page (`settings.picking.orchestration.{exclude,weight,defer,order,guarantee}`, `isHide: true`, never in the sidebar or settings search), and the five sub-pages share `OrchestrationRulePageBase` (`OrchestrationRulePages.cs` declares the five `[PageInfo]` classes): header + round picker + rule hint + search/count toolbar + a member list whose rows are toggles, a weight box, or position numbers with up/down buttons — so a member's 排斥/延后/权重/位置 is edited in exactly one place and `OrchestrationMemberDrawer` no longer exists. The overview hands `(profileId, round)` to the sub-page through `OrchestrationEditingSession` instead of letting a hidden page guess its context, and reloads on return so a sub-page save is visible immediately. The editor drawer (`OrchestrationEditorDrawer.axaml(.cs)`) still creates/rebinds a profile and immediately imports the source roster's members. A channel-status strip names the bound channel's draw mode through the same `Effective*Settings` the draw itself reads, warns when the selected list is not active, and offers 切换为编排抽取 that goes through `DrawModeSelection.SelectOrchestrated` on `RollCallSettingsConfig`/`LotterySettingsConfig` (so the previous repeat policy is kept for when the user switches back) — a list whose channel is not orchestrated would otherwise look perfectly enabled and never be read. 随机顺序 / 复制到其他轮 / 清空名单 live on the 顺序 sub-page (clear removes only that one list), and every write goes through the profile mutators (`SetExcluded`/`SetSkipped`/`SetGuaranteed`/`SetOrder`/`SetWeight`) so the cross-list invariants hold even in a hand-edited file. Because those mutators silently dissolve a conflicting entry in another list, every click that would do so asks first: a `FAContentDialog` lists the lists (and rounds) that will be cancelled, 取消 restores the `OneWay`-bound checkbox, 随机顺序 / 复制到其他轮 warn when 必中 members would be moved out, and the overview's 顺序/必中 switches say which sibling they will close. The proof is still generated: `SequentialOrder`(4) sampling with `StudentOrchestrated`(19)/`LotteryOrchestrated`(20) commits the positions in the candidate weight slot, and the audit carries only `fairness.orchestration = {round, roundCount}` (e.g. engine v3.6.0, see `docs/proof-orchestration-protocol.md`). Roll call, quick draw, and lottery all take the same branch and advance the round when the round is exhausted or reset; with no active 编排名单 the channel falls back silently to the ordinary random draw, and the main pages expose no orchestration state. | +| Random-number draw settings (随机数抽取) | `SecRandom.Core/Models/SubConfigs/Picking/RandomNumberSettingsConfig.cs`, `SecRandom/Views/SettingsPages/Picking/RandomNumberSettingsPage.axaml(.cs)`, `SecRandom.Core/Services/Stats/RandomNumberStatisticsService.cs`, `SecRandom/Views/SettingsPages/HomeSettingsPage.axaml(.cs)` | The independent page for the former 不使用名单 mode: it owns only the two default ranges and the reset behavior, never roster history. Number draws write no `HistoryItem`; the only durable record is `data/history/random-number/stats.json` (`SecRandomRandomNumberStats/v1`), written after a successful number commit. Its `Ranges` list accumulates a draw count and last-draw time per `(start,end)` range; the 100-row `Recent` list is retained only for compatibility and legacy derivation. The overview reads `Ranges` and shows one row per range (range, draw count, last draw) — never individual drawn numbers or per-draw results. `RandomNumberResetBehavior.TemporaryOnly` (default) clears only `__number_list__`/`__number_prize_pool__`; `TemporaryAndStatistics` also clears that stats file, while roster history is never touched. Ranges are clamped to `RosterSelection.MaxNumberRangeSpan` and the main pages apply the configured defaults at construction. | +| 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. The scope above is a **read** decision only: `HistoryGroupScope.ResolveRecordGroup` (same file, and deliberately **without** the feature switch) decides the marker each channel *writes*, so a channel whose draw is not group-scoped still stamps its own configured default group — turning the feature off must never fold 点名/闪抽/抽奖/编排 into the default group, because switching it back on could not undo that. | | 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`). | @@ -113,6 +115,7 @@ Keep this map short and stable. When code moves, AI agents should re-read the mo | `CrashRecoveryRuntime` | app service helper | `SecRandom/Services/CrashRecovery/CrashRecoveryRuntime.cs` | Reads crash recovery mode, writes bounded crash reports, and builds restart process plans. | | `ISecurityService` | app service contract | `SecRandom/Services/Security/` | Owns credential verification, lockout policy, selected-factor authorization, and protected-operation gating. | | `ProtocolCommandRouter` | app service | `SecRandom/Services/Ipc/ProtocolCommandRouter.cs` | Normalizes URL/IPC routes, routes protected commands, and returns structured IPC results. | +| `IntegrationChannelService` | app service | `SecRandom/Services/Integration/IntegrationChannelService.cs` | Verifies official SDK process proofs, discovers/persists approved local notification channels, forwards committed draws, and tracks IPC linkage leases. | | `DeviceUuidStore` | app service | `SecRandom/Services/Config/DeviceUuidStore.cs` | Persists the pseudo-anonymous device UUID separately in `data/config/device-uuid.json` and migrates legacy settings values. | | `AttachedSettingsRegistryService` | registry | `SecRandom.Core/Services/AttachedSettingsRegistryService.cs` | Static collections for attached-settings controls. | | `ViewModelBase` | base VM | `SecRandom/ViewModels/ViewModelBase.cs` | Base VM exposing `MainConfig`; inherits `ObservableRecipient`. | @@ -135,9 +138,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`. | @@ -151,6 +151,7 @@ Keep this map short and stable. When code moves, AI agents should re-read the mo - Selecting `TopmostMode.UiAccess` for the primary or floating window persists the setting and requests a restart. `SecRandom.Desktop/UiAccessStartup` is the Windows-only pre-Avalonia launcher boundary: following `killtimer0/uiaccess`, it elevates a bootstrap process, impersonates same-session `winlogon.exe`, sets `TokenUIAccess` on a duplicate of the bootstrap's current token, and starts the UIAccess replacement before Avalonia initializes. The original process waits only for the bootstrap to create the replacement, never for Avalonia or Host initialization; denied elevation, preparation failure, or timeout keeps the original process in ordinary topmost and preserves the configured mode for a later retry. - Windows UIAccess topmost builds may use `SecRandom.Desktop/app.uiaccess.manifest` when `EnableUiAccess=true`; that manifest requires Authenticode signing and installation under Program Files. Independently, the runtime `UiAccessStartup` token preparation follows `killtimer0/uiaccess` and works from the ordinary manifest after UAC authorization, so debug and portable Windows builds can exercise UIAccess as well. The release workflow enables the manifest only when Windows code-signing secrets are available. - Point-call students and lottery prizes use `RecordId` as the internal stable identity for history/fairness. The visible `Id` field is optional display metadata only and must not be required by import, draw, or history logic. +- Zero lists is a normal state, not an error: every list and prize pool may be deleted, including the last one. `ProfileService` seeds one blank `default` list/pool only on the first run (`MainConfigModel.General.Basic.GuideCompleted == false`) and only while that directory has no `*.json`; once the guide is complete an empty directory stays empty across restarts, because `ResolveProfileName` returns `null` instead of falling back to `"default"`. With no lists, `StudentListConfig`/`StudentHistoryConfig`/`PrizeListConfig`/`PrizeHistoryConfig` are all `null` (so `Current*` are `null` too); `Load*Profile(string.Empty)` means "detach the active profile" (`Clear*Profile`), `ProfileCatalogManager.Delete{Student,Prize}List` calls it when the deleted profile was the last one, and `SetDefault{StudentList,PrizePool}` accepts an empty name to clear a default that pointed at a deleted list. All consumers must keep working through the nullable `IProfileService` contract (`?.`/`?? []`); never reintroduce a "at least one list must remain" guard. UI consequence: list-management pages show their `C_NoList`/`C_NoList_D` empty state, and the draw-settings default roster/pool cards hide themselves (`DefaultRosterSettingSource.HasRosters`) instead of offering an empty picker. - A roll-call student or lottery prize candidate must be enabled and have a nonblank `Id` or `Name`. Import may map either column and excludes rows where both are blank. - Picking `ClearRecord` controls temporary draw records only; do not clear persistent profile histories from that setting. RollCall and QuickDraw share the same student temporary record store, while Lottery uses prize temporary records. - Privacy settings split Sentry upload from online status reporting: `SentryTelemetryEnabled` only controls `SecRandom/Services/Telemetry/`, while `OnlineStatusMode` gates the SECTL online-status and usage-counter channels (`SecRandom/Services/OnlineStatusService.cs`, `PlatformUsageReportService`) but deliberately not `PlatformVersionReportService`. @@ -159,27 +160,27 @@ 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 position row on that page is a dropdown field (`SecRandom.Core/Controls/AnchorGridDropDown`) whose collapsed text is the current position's localized name and whose flyout holds the 3×3 dot grid (`SecRandom.Core/Controls/AnchorGridPicker`, styled by the paired `Controls/AnchorGridPicker.axaml` and `Controls/AnchorGridDropDown.axaml`) instead of a list of five text options: `NotificationWindowPosition` defines nine anchors — `Center`/`Top`/`Bottom`/`Left`/`Right` keep the legacy values 0–4 and the four corners are appended as 5–8, so no saved position ever moves to another cell — and both that page and `App.TryResolveQuickDrawNotificationTargetRect` read `NotificationWindowAnchorLayout` (`GridOrder` for the cell order, `Resolve` for the horizontal/vertical anchor), so the grid order and the window geometry cannot drift apart. Picking a dot writes the anchor back into the field's text and closes the flyout (arrow keys browse the grid while it stays open), and the offsets still fine-tune any anchor. Its auto-close countdown presentation is global on that same default channel too: `CountdownStyle` picks the text hint or the default outline, and the outline is one continuous 6px rounded ring that starts on the top edge just after the top-left corner and is eaten clockwise as the remaining time runs out — the same start point and sweep direction as the floating window's long-press progress ring (`BorderedProgressRing`), never four separately shrinking bars. The outline's colors are edited as three sibling cards on that page (color mode, gradient, single color): the gradient card holds exactly two `ColorPicker`s — `CountdownGradientStart` and `CountdownGradientEnd`, laid side by side with no connector glyph and no add/remove affordance — and fills every ring segment from the window's horizontal position so the self-coloured loop has no seam; `CountdownSolidColor` is the uniform alternative with no preview swatch of its own, and both color cards are hidden while the text hint is selected. 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. - Full IPC/URL compatibility is app-layer routed through `ProtocolCommandRouter`: structured current-user named-pipe IPC is additive to legacy `ShowMainWindow`/`Restart`/`Url:` delivery, and all external mutations must use `ISecurityService`. `data/*` queries must use non-mutating profile snapshots, never active-profile loading APIs. - `HistoryItem.DrawRoundId` identifies every record committed by one logical draw. Populate it for new history writes; IPC history projections group by it and must never expose internal `RecordId`. -- History record groups (历史记录组) are an optional second history dimension beside `HistoryItem.CourseName`, never a replacement: on the record `HistoryGroup` (empty marker = the default group) is set when the record is written and both filters apply together, so a gated draw reads and writes the intersection. The scope parameter is deliberately **tri-state** (`string? historyGroup`): `null` means do not filter on the group axis at all (feature off or selector hidden = the pre-#294 behaviour, every record counts), `""` means the default group only (records whose marker is empty, which is what the panel's 默认记录组 option selects), and a name means that one group. Collapsing `null` and `""` re-introduces the original unfairness in the other direction, because the option labelled 默认记录组 would then count records that were explicitly sorted into another group. `DrawEngine`'s history caches, `IProfileService.Record*History`, `IDrawCommitService` commit records, and `VerificationDrawCoordinator` carry the value as a trailing optional parameter — nothing in the weight calculator changes, because filtering the cache already yields the group-local counts. Deliberate limits: temporary draw records are bucketed per history record group (one bucket for "not scoped by a group", one for the default group, one per group name), so a group-scoped draw's repeat limit counts exactly the records it can see and switching groups never inherits another group's counts; renaming a group merges its bucket and deleting one folds it into the default bucket, while prize temporary records stay per prize pool because they carry physical inventory. The group name is the identity (renaming rewrites markers, and `HistoryGroupName` rejects blank/over-long/control/reserved names such as the `__break__` course sentinel), and the group *selection* is transient UI state — it is never persisted, and hiding the selector always means "no group scope" (`null`, i.e. every record counts again), so a stale selection can never silently keep filtering. The switch and the group create/rename/delete management live on the history-management settings page (`SecRandom/Views/SettingsPages/History/HistoryManagementSettingsPage.axaml(.cs)`), not on a draw-settings page, and the main panels expose only the selector. Moving records between groups goes through `IProfileCatalogManager.Move{Student,Prize}HistoryGroup` (marker-only, no new record, no `DrawRoundId`) and never through `IDrawCommitService`. Enabling the feature is not a protected operation, the switch is readable-but-not-writable through the control plane, and downgrading to a build without it silently folds grouped records back into the global history. +- History record groups (历史记录组) are an optional second history dimension beside `HistoryItem.CourseName`, never a replacement: on the record `HistoryGroup` (empty marker = the default group) is set when the record is written and both filters apply together, so a gated draw reads and writes the intersection. The scope parameter is deliberately **tri-state** (`string? historyGroup`): `null` means do not filter on the group axis at all (feature off or selector hidden = the pre-#294 behaviour, every record counts), `""` means the default group only (records whose marker is empty, which is what the panel's 默认记录组 option selects), and a name means that one group. Collapsing `null` and `""` re-introduces the original unfairness in the other direction, because the option labelled 默认记录组 would then count records that were explicitly sorted into another group. `DrawEngine`'s history caches, `IProfileService.Record*History`, `IDrawCommitService` commit records, and `VerificationDrawCoordinator` carry the value as a trailing optional parameter — nothing in the weight calculator changes, because filtering the cache already yields the group-local counts. Deliberate limits: temporary draw records are bucketed per history record group (one bucket for "not scoped by a group", one for the default group, one per group name), so a group-scoped draw's repeat limit counts exactly the records it can see and switching groups never inherits another group's counts; renaming a group merges its bucket and deleting one folds it into the default bucket, while prize temporary records stay per prize pool because they carry physical inventory. The group name is the identity (renaming rewrites markers, and `HistoryGroupName` rejects blank/over-long/control/reserved names such as the `__break__` course sentinel), and the group *selection* is transient UI state — it is never persisted, and hiding the selector always means "no group scope" (`null`, i.e. every record counts again), so a stale selection can never silently keep filtering. The switch and the group create/rename/delete management live on the history-management settings page (`SecRandom/Views/SettingsPages/History/HistoryManagementSettingsPage.axaml(.cs)`), not on a draw-settings page, and the main panels expose only the selector. Moving records between groups goes through `IProfileCatalogManager.Move{Student,Prize}HistoryGroup` (marker-only, no new record, no `DrawRoundId`) and never through `IDrawCommitService`. Enabling the feature is not a protected operation, the switch is readable-but-not-writable through the control plane, and downgrading to a build without it silently folds grouped records back into the global history. Read scope and write marker are separate values on every commit: `HistoryGroup` stays the tri-state **read** scope, while `RecordGroup` (and `StudentRecordGroup` for the students assigned by a lottery round, whose records live in the student history rather than the prize history) is the **write** marker and is resolved by `HistoryGroupScope.ResolveRecordGroup`, which never takes the feature switch — `DrawCommitCoordinator` uses `RecordGroup ?? HistoryGroup`, so every existing caller keeps its old behaviour byte-for-byte, and `RollCallSession`/`LotterySession` (mobile), `RollCallDrawService`/`LotteryDrawService` and `QuickDrawPageViewModel` always pass one, so a channel that is not group-scoped still writes its own configured default group instead of collapsing into the default one. +- Moving records between groups (`IProfileCatalogManager.Move{Student,Prize}HistoryGroup`) is a marker-only operation and must never go through `IDrawCommitService`. Its optional trailing `sourceGroup` scopes the rewrite to one record group (`null` = every record of the selected member, `""` = only the default group, a name = that group), because a history page filtered to a group must not silently rewrite the member's records sitting in other groups; the returned count is the number of `HistoryItem`s whose marker changed, and `0` leaves the file byte-identical. The selection unit is the member's `RecordId` — every record of one member shares it — so a summary/overview row is movable too, which is why `HistoryDisplayRow.RecordId` is populated for overview rows as well. Creating a group is not part of moving: the move flyout offers only the default group plus existing groups, and create/rename/delete stays on `HistoryManagementSettingsPage`. The lottery page shows its record-group selector even without an assigned student list: nothing is isolated then, but the chosen name still tags the prize records it writes (a number-only draw writes no history at all and therefore hides the selector). - Draw commits must go through `IDrawCommitService` (`DrawCommitCoordinator`): one logical draw gets exactly one `DrawRoundId` (a caller may supply one), temporary records commit before persistent history, a mid-commit failure rolls back through snapshot compensation, and commits serialize behind the coordinator gate. Never reintroduce bare two-step writes of `IProfileService.Record*History` plus temporary-record calls; the optional `drawRoundId` parameter (and `drawMethod` on `RecordPrizeHistory`) exists for coordinator use. Preview frames write no temporary record and no history: the coordinator is the only writer of the fairness surface, and the weight/filter/verification layers read persistent history only, so an animation that flickers through a hundred names can neither record a hit nor shift a weight. A preview shuffles with `Random.Shared` while the draw samples through the injected `IRandomSource` (`CryptoRandomSource`), so animation frames cannot consume or bias the draw's random stream. `SecRandom.Core.Tests/PreviewAnimationFairnessTests.cs` pins all three claims, including a reflection guard that the presentation contracts expose no commit or temporary-record surface. - 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. +- 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.6/3.5/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. Engine v3.6.0 adds the orchestrated generation: `samplingMode` 4 (`SequentialOrder`) reads the arranged position out of the weight slot (`weightMicros = 1..count`, dense and unique, no random material consumed), `algorithmProfile` 19/20 (`StudentOrchestrated`/`LotteryOrchestrated`) is compatible only with that sampler, and the anonymous audit declares the mode as `fairness.repeatMode = "orchestrated"` plus `fairness.orchestration = { round, roundCount }` — counters only, never the schedule, positions, names, or weights. Deploy the service before a client build sends 3.6: an older version chain rejects it outright. The four draw-mode tokens live in `SecRandom.Core/Enums/Configs/DrawModeCatalog.cs`, which is the only client-side spelling of them. - 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 +194,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`. @@ -218,9 +218,10 @@ Keep this map short and stable. When code moves, AI agents should re-read the mo - Managed draw music uses a platform-specific runtime boundary: desktop `settings.personalized.music` imports/deletes/previews MP3/WAV/FLAC files through `MusicLibraryService`/private SoundFlow playback, while mobile `MobileMediaLibraryService` uses StorageProvider streams into `data/audio/music` and `IMobileMediaPlayer` supplied by Android/iOS heads. Draw-settings and student/prize attached settings use the same managed IDs, no-music, or random-play options; the first drawn record supplies both overrides for a multi-record result. Deleting a managed track clears global and per-record references. Mobile display images likewise import through StorageProvider streams into `data/images`; image/music/voice failures must not invalidate a committed draw. - 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. +- `LinkageSettings.VerificationRequired` governs the course-time bypass prompt and is distinct from `SecuritySettings.ProtectLinkage`, which continues to protect only external SecRandom URL/IPC mutations. That bypass is only a bypass if something can actually verify: `SecurityService.AuthorizeAsync` runs the action unchecked when `RequiresVerification` is false (security protection off, or no configured factor), so `LinkageDrawCoordinator` must ask `RequiresVerification(SecurityOperation.BypassClassTimeRestriction)` first and hard-block — including the `ClassTimeDrawRestrictionNotice` toast — instead of delegating, or the break ban and `LinkageSettings.RestrictWhenUnavailable` fail open. `EvaluateGate` mirrors the same test and answers `BlockedByClassTime`. Student course history uses `HistoryItem.CourseName` with `RecordId` identity; empty legacy course values remain global history. +- 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/CHANGELOG/v3/v3.2.0-beta.1/CHANGELOG.md b/CHANGELOG/v3/v3.2.0-beta.1/CHANGELOG.md new file mode 100644 index 000000000..e1edb1618 --- /dev/null +++ b/CHANGELOG/v3/v3.2.0-beta.1/CHANGELOG.md @@ -0,0 +1,63 @@ +新版本 + +> [!caution] +> +> # 抢先体验 Beta 版 +> +> 您正在使用我们的最新功能预览版。为了在正式版中给您带来更完美的体验,我们需要您的帮助与反馈。 +> +> **⚠️ 风险提示**:此版本尚在打磨中,可能存在偶发异常或未知问题,**请务必避免用于关键业务或生产环境**。 +> +> **📣 我们需要您**:如果发现任何 Bug,或有功能改进建议,欢迎随时前往 **GitHub Issues** 提交反馈。 +> +> 感谢您成为我们的首批体验官! + + +# v3.2.0 - Beta 1 - Nonomi (十六夜野宫) + +## 🚀 主要更新 + +- 新增 **浮窗支持屏幕两侧**,开启后可以更方便的让你进行快速操作 +- 新增 **历史记录组**,开启后可以在点名/抽奖页面设置接下来抽取的历史记录存放在哪个历史记录组内。如果使用公平抽取模式,将会影响后续的公平性 +- 新增 **随机数模式**,可在点名/抽奖的名单中选择随机数给你,将可以直接进行随机数的抽取。随机数的默认值可在设置内调整 +- 新增 **简洁模式**,主要是部分用户想要一个最简单的抽取样式,你如果觉得你使用 SecRandom 只用了点名名单和闪抽,那你可以使用这个功能,当然没有多余的娱乐功能了 +- 新增 **全屏通知渠道**,可以全屏显示结果,并且有动画样式可以选择,而且可以配置背景图片,能让抽取更有意思。“打字机”动画支持文案库,你也可以手动添加,或者发送内置提示词给AI生成后进行粘贴导入 +- 新增 **浮窗通知设置页面**,可以配置浮窗的一些功能,以及样式 +- 新增 **浮窗组件可自定义**,可以自定义配置浮窗内的组件,并且支持打开其他文件/URL,支持自定义名称、图标 +- 新增 **浮窗收纳样式可自定义**,为了一些用户觉得“抽”和单一的图标觉得标识不明显,可以自行配置该样式 +- 新增 **课程联动严格限制功能**,可以防止IPC断联时依旧保持安全锁定状态,默认关闭 +- 新增 **浮窗通知自适应前景色**,支持自动根据背景调整浮窗通知的外观,大大提升了可读性。该功能默认开启,如果开启低配模式将会自动关闭 +- 新增 **更新源**,支持了思拓创联官方服务器分发源 +- 新增 **关于-本机信息**,可在关于页面查看本机的一些信息 +- 新增 **关于-抽取算法版本号**,支持在关于页面查看抽取算法的版本号 +- 新增 **浮窗支持无焦点**,为防止点击浮窗时出现焦点切换,导致影响PPT的放映,支持开启,如果在部分系统环境下有Bug可以自行关闭 +- 新增 **编排模式**,可以在部分场景(eg:公开课、演示等)进行一个固定顺序/权重修改/排除一些成员/延后一些成员滞后抽取,对部分不需要随机/公平抽取的场景进行支持 +- 新增 **闪抽长按支持抽多人**,默认开启,长按闪抽可出现数量显示组件在左侧/右侧,上下拖动后松手即可快速抽取多人(1~5人) +- 新增 **公平抽取设置值**,可选择公平抽取算法倾向,分为 **均匀优先(默认)、随机优先**,修改为随机优先后可以有细微感知抽取的随机性会稍强,如果担心被台下的人骂,我建议还是均匀优先好一点 +- 新增 **浮窗通知关闭倒计时样式**,默认设置为“四周进度”,汇总浮窗通知的四周显示关闭倒计时,并且可以自定义颜色,默认为蓝红渐变 +- 新增 **数据储存**,可以手动修改数据默认保存的位置,并且支持一键迁移 + +## 💡 功能优化 + +- 优化 **名单管理增减成员/奖品体验**,单独添加/减少一位成员序号重叠/缺失会自动询问用户该执行推后/不动行为 +- 优化 **登录后授权的页面**,变得……好看了 +- 优化 **IPC接口**,拓展了部分接口的功能,并且优化了IPC部分管道名称 +- 优化 **部分名称优化**,将“SecRandom 文档站”改为“SecRandom 官网”、“SecRandom 内置通知”改为“SecRandom 浮窗通知” +- 优化 **集控**,支持思拓创联官方集控API接口,旧的集控将不可使用,桌面端支持地点码+配对码/登录账号的形式进行连接集控;移动端登录账号后即可远程抽取对应设备上的特定名单 +- 优化 **历史记录**,将每种抽取模式的默认历史分开计算,避免影响公平抽取的计算 +- 优化 **CPU占用&RAM占用**,这一次只能说是降低了部分,下次再接再厉 +- 优化 **浮窗点击**,小修小补了浮窗的点击准确性 + +## 🐛 修复问题 + +- 修复 **便携版开机启动项指向版本文件夹**,便携包的自启动与 `secrandom://` 协议注册现在指向包根目录的 `SecRandomLauncher`,而不是 `app-*` 版本目录里的 `SecRandom.Desktop.exe` +- 修复 **Edge TTS 生成报错**,更新库版本支持了v2版本 +- 修复 **默认数据目录存放位置**,修复在便携模式下和安装版本下的数据目录的默认存放位置不标准的情况 + +## ❌ 移除功能 + +- 移除 证明文件验证链、云服务自动备份、软件启动时检查文件是否被篡改功能(第一用处不大,第二有些功能有点 bug) + +--- + +💝 **感谢所有贡献者为 SecRandom 项目付出的努力!** diff --git a/CHANGELOG/v3/v3.2.0/CHANGELOG.md b/CHANGELOG/v3/v3.2.0/CHANGELOG.md deleted file mode 100644 index 7a7a11b97..000000000 --- a/CHANGELOG/v3/v3.2.0/CHANGELOG.md +++ /dev/null @@ -1,43 +0,0 @@ -新版本 - -> [!note] -> -> # v3.2.0 正式版发布 -> -> 感谢您一路以来的等待与支持,**v3.2.0 正式版**现已发布,可直接用于日常教学等正式场景。 -> -> **📣 我们需要您**:如果发现任何 Bug,或有功能改进建议,欢迎随时前往 **GitHub Issues** 提交反馈。 -> -> 感谢您陪伴 SecRandom 一路走到这里! - - -# v3.2.0 - Nonomi (十六夜野宫) - -## 🚀 主要更新 - -- 新增 **历史记录组**:同一个名单的历史可以被拆成互不干扰的若干组(例如「课堂提问」和「抽奖」),在点名、抽奖主页面选一个组即可把抽取锁定到该组——权重只参考这一组里已有的记录,本次记录也只写进这一组 -- 新增 **组管理**:在「设置 → 历史记录 → 历史记录管理」里可以新建、改名、删除记录组;删除只会把该组记录移回默认组,不会删除任何一条历史 -- 新增 **历史页的记录组列与筛选**,并支持把已有记录「移到另一组」,用来修复选错组的记录或把旧记录归档 -- 新增 **首页「默认记录组」选项**:点名页、抽奖页的记录组下拉里,第一项是「默认记录组」,选它表示只按未分组的记录计算权重——已经分到别的组的记录不会混进来;主页面只保留这一个下拉,不再有锁定提示或取消按钮 -- 新增 **导出包含记录组列**:导出的 XLSX/CSV 明细多一列记录组,便于按用途核对 -- 新增 **闪抽默认记录组**:闪抽没有自己的选择器,改为在「抽取设置 → 闪抽」里设一个默认组,之后每次闪抽都锁在该组(悬浮窗上会有一行提示说明当前锁定到哪个组) -- 新增 **点名/抽奖的持久化默认记录组**:在两页各自「抽取设置」里可以指定下次打开时组下拉默认落在哪一组——下拉本身仍然只是本次会话的临时选择,改动设置里的默认组才会影响下一次打开;选「默认记录组」表示只算未分组的记录,与「不分组(全部历史)」不是一回事 -- 新增 **默认组失效回落**:设置里的组被删除或改名后,下一次抽取自动回落到「默认记录组」(删除组只会把它的记录移回默认组),闪抽提示里还会多一句说明原组已不存在 -- 新增 **证明声明整理范围**:可验证抽奖的证明里会写明本次权重用的是哪一个范围的历史(全局 / 课程 / 记录组 / 课程加记录组),验证端据此按同样的范围重放;证明引擎版本随之升到 3.4.0 - -## 💡 功能优化 - -- 优化 **课程过滤与记录组可以同时使用**:开了课程联动过滤时,两个维度取交集,互不覆盖 -- 优化 **抽奖页的分配学生权重**:抽奖页选择记录组后,分配给奖品的学生也按该组的历史计算权重 -- 优化 **重复抽取上限按记录组独立计数**:临时记录里的「已抽中次数」现在按记录组分开存(不分组、默认组、每个具名组各一份),换组不会再把上一组的计数带过来;改名组会把计数合并到新名字,删除组会把计数并入默认组。升级前的历史计数无法判断属于哪个组,统一归到「不分组」那一份,按组计数从零开始 -- 优化 **历史记录改用轻量数据库存储**:每个名单/奖池的历史现在是一个小的 SQLite 数据库(`data/history/**/*.srhdb`),保存只写本次变动的成员与记录,不再每次把整份历史重新序列化。以 60 人 × 300 轮(1.8 万条记录)为例:整份保存从约 112 ms 降到 35 ms、一次抽取的增量保存约 37 ms,文件体积从 9.4 MB 降到 1.9 MB,读取也略快;备份、云备份、还原与导入导出仍然按整个 `data/history` 目录处理,不需要额外操作 -- 新增 **历史记录无感迁移**:升级后第一次读取某个名单/奖池时,旧的历史 JSON 会自动导入新数据库,原文件改名成 `*.json.migrated` 留作一次性回滚副本(不再参与任何 JSON 读取)。不需要手动迁移,恢复旧版备份包(里面是 JSON)后同样会被自动导入 -- 注意 **降级需要手动换回 JSON**:旧版本只认识历史 JSON,回退到旧版本前请把 `data/history/**/*.json.migrated` 改名回 `*.json`,否则旧版本看不到这些名单的历史记录 - -## 🐛 修复问题 - -- 修复 **便携版开机启动项指向版本文件夹**:便携包的自启动与 `secrandom://` 协议注册现在指向包根目录的 `SecRandomLauncher`,而不是 `app-*` 版本目录里的 `SecRandom.Desktop.exe`;更新替换版本目录后开机启动不再失效,也无需重新设置,已有的旧条目会在下次启动时自动改写 - ---- - -💝 **感谢所有贡献者为 SecRandom 项目付出的努力!** diff --git a/SecRandom.Core.Tests/AdaptiveBackdropTests.cs b/SecRandom.Core.Tests/AdaptiveBackdropTests.cs new file mode 100644 index 000000000..182f6226a --- /dev/null +++ b/SecRandom.Core.Tests/AdaptiveBackdropTests.cs @@ -0,0 +1,233 @@ +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); + } + + /// + /// 需求本身:浅底必须黑字、深底必须白字,判据是"画出来的卡片有多亮",不是"桌面深不深"。 + /// + [Theory] + [InlineData(0.00)] + [InlineData(0.18)] + [InlineData(0.50)] + [InlineData(0.82)] + [InlineData(1.00)] + public void SelectsTheHigherContrastInkForTheDrawnSurface(double surfaceLuminance) + { + var ink = AdaptiveBackdropResolver.SelectForeground(surfaceLuminance); + + Assert.True( + AdaptiveBackdropResolver.ContrastRatio(surfaceLuminance, ink) >= + AdaptiveBackdropResolver.ContrastRatio( + surfaceLuminance, + ink == Colors.Black ? Colors.White : Colors.Black)); + Assert.Equal(surfaceLuminance >= 0.1792 ? Colors.Black : Colors.White, ink); + } + + /// 整体不透明度也淡化文字:中灰桌面上的淡深色卡片仍以白字较清晰,但无法达到 AA。 + [Fact] + public void WashedOutDarkCardComparesTheVisibleInkInsteadOfOpaqueInk() + { + var backdrop = BackdropLuminance.FromPercentiles(0.5, 0.5, 0.5); + var theme = AdaptiveBackdropResolver.Resolve(backdrop, appThemeIsDark: true, surfaceOpacity: 0.2); + + Assert.True(theme.IsDarkBackdrop); + Assert.Equal(Colors.White, theme.Foreground); + Assert.Equal(1.0, theme.SurfaceAlpha); + // 独立数值:L(#1F)=0.0137020830472897,底=.2*L(#1F)+.8*.5,白字=.2+.8*.5。 + Assert.Equal(0.402740416609458, theme.SurfaceLuminance, 12); + Assert.Equal(1.43570128964365, AdaptiveBackdropResolver.ContrastAgainstSurface(theme), 12); + Assert.Equal(1.43570128964365, + AdaptiveBackdropResolver.WorstContrastAcrossBackdrop(theme, backdrop), 12); + Assert.Equal(1.00608981468768, + AdaptiveBackdropResolver.WorstContrastAcrossBackdrop(theme with { Foreground = Colors.Black }, backdrop), 12); + Assert.True(AdaptiveBackdropResolver.ContrastAgainstSurface(theme) < AdaptiveBackdropResolver.MinimumContrastRatio); + } + + /// 合成亮度必须等于"卡片色 × 卡片不透明度 × 整块不透明度 + 剩下的桌面"。 + [Theory] + [InlineData(1.0)] + [InlineData(0.8)] + [InlineData(0.5)] + [InlineData(0.2)] + public void SurfaceLuminanceMatchesTheCompositionOfTheDrawnCard(double opacity) + { + const double backdropLuminance = 1.0; + var theme = AdaptiveBackdropResolver.Resolve( + BackdropLuminance.FromPercentiles(backdropLuminance, backdropLuminance, backdropLuminance), + appThemeIsDark: false, + surfaceOpacity: opacity); + + var expected = AdaptiveBackdropResolver.ComposeSurfaceLuminance( + theme.Surface, theme.SurfaceAlpha, backdropLuminance, opacity); + + Assert.Equal(expected, theme.SurfaceLuminance, 12); + // 文字也乘整体不透明度,白桌面上的黑字亮度为 1-opacity。 + var expectedContrast = (expected + 0.05) / (1 - opacity + 0.05); + Assert.Equal(expectedContrast, AdaptiveBackdropResolver.ContrastAgainstSurface(theme), 12); + if (opacity <= 0.5) + Assert.True(expectedContrast < AdaptiveBackdropResolver.MinimumContrastRatio); + } + + /// + /// 卡片半透明压在一张花壁纸/PPT 上时,卡片两端会合成出不同的底色;字必须在两端都看得清, + /// 否则就是"左边看得见、右边消失"。 + /// + [Theory] + [InlineData(0.02, 0.30, 0.62)] + [InlineData(0.05, 0.50, 0.98)] + [InlineData(0.10, 0.75, 0.95)] + public void KeepsTheInkReadableAtBothEndsOfABusyBackdrop(double p10, double median, double p90) + { + const double opacity = 0.9; + var backdrop = BackdropLuminance.FromPercentiles(p10, median, p90); + var theme = AdaptiveBackdropResolver.Resolve(backdrop, appThemeIsDark: false, surfaceOpacity: opacity); + + var worst = AdaptiveBackdropResolver.WorstContrastAcrossBackdrop(theme, backdrop, opacity); + + Assert.True( + worst >= AdaptiveBackdropResolver.MinimumContrastRatio, + $"p10={p10:0.00} median={median:0.00} p90={p90:0.00} worst={worst:0.00} " + + $"ink={(theme.Foreground == Colors.Black ? "black" : "white")} alpha={theme.SurfaceAlpha:0.00}"); + } + + /// + /// 不透明度低到"桌面透上来太多"时,任何纯色都达不到 4.5,此时只能选对比更高的那个, + /// 并且卡片底必须已经被压到不透明(在这条不透明度下已经无解,但仍要是最优解)。 + /// + [Fact] + public void PicksTheBestAvailableInkWhenTheCardIsTooTransparentToBeReadable() + { + const double opacity = 0.75; + var backdrop = BackdropLuminance.FromPercentiles(0, 0.2, 1); + var theme = AdaptiveBackdropResolver.Resolve(backdrop, appThemeIsDark: false, surfaceOpacity: opacity); + + Assert.Equal(1.0, theme.SurfaceAlpha, 3); + Assert.Equal(Colors.White, theme.Foreground); + // 整体透明度同时淡化文字,黑/白字在亮桌面端的可见对比度都不足 4.5。 + Assert.Equal(3.384077715267313, + AdaptiveBackdropResolver.WorstContrastAcrossBackdrop(theme, backdrop, opacity), 12); + Assert.Equal(1.0342552076182241, + AdaptiveBackdropResolver.WorstContrastAcrossBackdrop(theme with { Foreground = Colors.Black }, backdrop, opacity), 12); + Assert.True( + AdaptiveBackdropResolver.WorstContrastAcrossBackdrop(theme, backdrop, opacity) >= + AdaptiveBackdropResolver.WorstContrastAcrossBackdrop( + theme with { Foreground = Colors.Black }, + backdrop, + opacity)); + Assert.True( + AdaptiveBackdropResolver.WorstContrastAcrossBackdrop(theme, backdrop, opacity) >= + AdaptiveBackdropResolver.WorstContrastAcrossBackdrop( + theme with { Foreground = Colors.White }, + backdrop, + opacity)); + } + + /// 整体透明度不改变桌面分类,但可能让较清晰的白字也达不到目标对比度。 + [Fact] + public void SurfaceOpacityDoesNotReclassifyTheBackdrop() + { + var theme = AdaptiveBackdropResolver.Resolve( + BackdropLuminance.FromPercentiles(0.45, 0.45, 0.45), appThemeIsDark: true, surfaceOpacity: 0.05); + + Assert.True(theme.IsDarkBackdrop); + Assert.Equal(Colors.White, theme.Foreground); + Assert.True(AdaptiveBackdropResolver.ContrastAgainstSurface(theme) < AdaptiveBackdropResolver.MinimumContrastRatio); + } + + [Fact] + public void KeepsTheBetterTranslucentSurfaceWhenNoCandidateMeetsTheContrastTarget() + { + var backdrop = BackdropLuminance.FromPercentiles(0, 0.8, 1); + var theme = AdaptiveBackdropResolver.Resolve(backdrop, appThemeIsDark: false, surfaceOpacity: 0.75); + + Assert.Equal(Colors.Black, theme.Foreground); + Assert.Equal(224, theme.Surface.A); + // 白底本身越实,亮桌面上的淡黑字反而越贴近底色;不能无条件返回 alpha=1。 + Assert.Equal(3.4033140306651, + AdaptiveBackdropResolver.WorstContrastAcrossBackdrop(theme, backdrop), 12); + var opaqueSurface = theme with { Surface = Color.FromRgb(0xFA, 0xFA, 0xFA) }; + Assert.Equal(3.38993338312322, + AdaptiveBackdropResolver.WorstContrastAcrossBackdrop(opaqueSurface, backdrop), 12); + } +} \ No newline at end of file diff --git a/SecRandom.Core.Tests/AppHostServiceResolutionTests.cs b/SecRandom.Core.Tests/AppHostServiceResolutionTests.cs new file mode 100644 index 000000000..b1f264779 --- /dev/null +++ b/SecRandom.Core.Tests/AppHostServiceResolutionTests.cs @@ -0,0 +1,80 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using SecRandom.Core.Abstraction; + +namespace SecRandom.Core.Tests; + +/// +/// 的取服务边界。停机流程会先释放服务容器、再清空 Host, +/// 这个窗口里错误处理路径仍会取服务;此时必须得到 null 而不是把 ObjectDisposedException 抛回去, +/// 否则一次停机期的刷新(例如托盘 Sudo 菜单的 5 秒计时器)会二次击穿异常处理。 +/// +[Collection("AppHost")] +public class AppHostServiceResolutionTests : IDisposable +{ + private readonly IHost? _originalHost = IAppHost.Host; + + public void Dispose() + { + IAppHost.Host = _originalHost; + } + + [Fact] + public void TryGetService_ReturnsNull_WhenHostIsNotBuilt() + { + IAppHost.Host = null; + + Assert.Null(IAppHost.TryGetService()); + } + + [Fact] + public void TryGetService_ReturnsNull_WhenProviderIsDisposed() + { + var provider = new ServiceCollection().AddSingleton(new object()).BuildServiceProvider(); + provider.Dispose(); + IAppHost.Host = new StubHost(provider); + + Assert.Null(IAppHost.TryGetService()); + } + + [Fact] + public void TryGetService_ReturnsNull_WhenServiceIsNotRegistered() + { + IAppHost.Host = new StubHost(new ServiceCollection().BuildServiceProvider()); + + Assert.Null(IAppHost.TryGetService()); + } + + [Fact] + public void TryGetService_ReturnsRegisteredService() + { + var service = new object(); + IAppHost.Host = new StubHost(new ServiceCollection().AddSingleton(service).BuildServiceProvider()); + + Assert.Same(service, IAppHost.TryGetService()); + } + + [Fact] + public void GetService_StillThrows_WhenHostIsNotBuilt() + { + IAppHost.Host = null; + + Assert.Throws(() => + { + IAppHost.GetService(); + }); + } + + private sealed class StubHost(IServiceProvider services) : IHost + { + public IServiceProvider Services { get; } = services; + + public Task StartAsync(CancellationToken cancellationToken = default) => Task.CompletedTask; + + public Task StopAsync(CancellationToken cancellationToken = default) => Task.CompletedTask; + + public void Dispose() + { + } + } +} \ No newline at end of file diff --git a/SecRandom.Core.Tests/AutomationIpcTests.cs b/SecRandom.Core.Tests/AutomationIpcTests.cs new file mode 100644 index 000000000..50ee290d2 --- /dev/null +++ b/SecRandom.Core.Tests/AutomationIpcTests.cs @@ -0,0 +1,78 @@ +using System.Text.Json; +using SecRandom.Core.Services.Ipc; +using SecRandom.Shared.Models.Ipc; + +namespace SecRandom.Core.Tests; + +public class AutomationIpcTests +{ + [Fact] + public void V2Request_ParsesDocumentedEnvelope() + { + const string line = """ + {"version":2,"type":"rpc","id":"7","method":"system.ping","params":{}} + """; + + var ok = IpcV2RequestEnvelope.TryRead(line, out var request, out var error); + + Assert.True(ok, error?.Message); + Assert.NotNull(request); + Assert.Equal("7", request!.Id); + Assert.Equal("system.ping", request.Method); + } + + [Fact] + public void V2Request_RejectsV1AndUnknownTypes() + { + Assert.False(IpcV2RequestEnvelope.TryRead( + """{"version":1,"type":"url","payload":{"url":"data/roll_call_list?name=a"}}""", + out _, out var versionError)); + Assert.Equal(AutomationErrorCodes.UnsupportedVersion, versionError!.Code); + + Assert.False(IpcV2RequestEnvelope.TryRead( + """{"version":2,"type":"event","event":"x"}""", + out _, out var typeError)); + Assert.Equal(AutomationErrorCodes.InvalidRequest, typeError!.Code); + } + + [Fact] + public void V2Response_SerializesOkAndErrorBranches() + { + var success = JsonSerializer.Serialize( + IpcV2ResponseEnvelope.Success("1", new { pong = true }), + new JsonSerializerOptions(JsonSerializerDefaults.Web)); + Assert.Contains("\"ok\":true", success); + Assert.Contains("\"pong\":true", success); + + var failure = JsonSerializer.Serialize( + IpcV2ResponseEnvelope.Failure("2", IpcV2ErrorEnvelope.Create("busy", "忙", true)), + new JsonSerializerOptions(JsonSerializerDefaults.Web)); + Assert.Contains("\"ok\":false", failure); + Assert.Contains("\"retryable\":true", failure); + } + + [Fact] + public void CommandCatalog_IsUniqueAndStable() + { + var methods = AutomationCommandCatalog.Methods; + Assert.Equal(37, methods.Count); + Assert.Equal(methods.Count, methods.Select(m => m.Name).Distinct(StringComparer.Ordinal).Count()); + Assert.All(methods, m => Assert.False(string.IsNullOrWhiteSpace(m.Name))); + Assert.NotNull(AutomationCommandCatalog.Find("draw.quick.trigger")); + Assert.Null(AutomationCommandCatalog.Find("nope")); + } + + [Fact] + public void ErrorCodes_AreLowerCaseSnakeCase() + { + var codes = typeof(AutomationErrorCodes) + .GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static) + .Where(f => f.IsLiteral) + .Select(f => (string)f.GetRawConstantValue()!) + .ToList(); + + Assert.Contains(AutomationErrorCodes.IpcDisabled, codes); + Assert.Contains(AutomationErrorCodes.UrlActivationForbidden, codes); + Assert.All(codes, c => Assert.Matches("^[a-z][a-z0-9_]*$", c)); + } +} \ No newline at end of file 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/ControlNodeEnrollmentChannelTests.cs b/SecRandom.Core.Tests/ControlNodeEnrollmentChannelTests.cs index 752a167ec..dfb2864de 100644 --- a/SecRandom.Core.Tests/ControlNodeEnrollmentChannelTests.cs +++ b/SecRandom.Core.Tests/ControlNodeEnrollmentChannelTests.cs @@ -199,7 +199,7 @@ await Assert.ThrowsAsync(() => } [Fact] - public async Task 分班请求携带classId_允许传null表示不分班() + public async Task 分班请求携带classId_空值表示解除班级() { string? captured = "not-set"; var handler = new FakeHandler(request => @@ -209,14 +209,55 @@ await Assert.ThrowsAsync(() => captured = body.TryGetProperty("classId", out var classId) && classId.ValueKind != JsonValueKind.Null ? classId.GetString() : null; - return Json(HttpStatusCode.OK, """{ "ok": true }"""); + return Json(HttpStatusCode.OK, """{ "ok": true, "device": { "id": "dev-1", "classId": "" } }"""); }); await CreateClient(handler).AssignClassAsync(Credential, "c1"); Assert.Equal("c1", captured); + // 换班是两步:先解除(classId = null),再绑定新班级。服务端两种都收。 await CreateClient(handler).AssignClassAsync(Credential, null); Assert.Null(captured); + + await CreateClient(handler).AssignClassAsync(Credential, " "); + Assert.Null(captured); + } + + [Fact] + public async Task 解除接入走device_unenroll并携带设备凭据() + { + var handler = new FakeHandler(request => + { + Assert.Equal(HttpMethod.Post, request.Method); + Assert.Equal("/control/api/device/unenroll", request.RequestUri!.AbsolutePath); + var body = JsonDocument.Parse(ReadBody(request)).RootElement; + Assert.Equal("dev-1", body.GetProperty("deviceId").GetString()); + Assert.Equal("secret-1", body.GetProperty("secret").GetString()); + // 解除接入只证明"我是谁",不该顺带传班级或地点:服务端按 secret 自己解析。 + Assert.False(body.TryGetProperty("classId", out _)); + Assert.False(body.TryGetProperty("siteId", out _)); + return Json(HttpStatusCode.OK, """{ "ok": true, "data": { "deviceId": "dev-1" } }"""); + }); + + await CreateClient(handler).UnenrollAsync(Credential); + } + + [Theory] + [InlineData(HttpStatusCode.Unauthorized, "bad_secret", NodeEnrollmentFailure.CodeNotFound)] + [InlineData(HttpStatusCode.Unauthorized, "device_revoked", NodeEnrollmentFailure.CodeRevoked)] + [InlineData(HttpStatusCode.NotFound, "device_not_found", NodeEnrollmentFailure.Unknown)] + public async Task 解除接入的失败码仍可区分( + HttpStatusCode status, + string code, + NodeEnrollmentFailure expected) + { + var handler = new FakeHandler(_ => Json(status, $$"""{ "code": "{{code}}" }""")); + + var exception = await Assert.ThrowsAsync(() => + CreateClient(handler).UnenrollAsync(Credential)); + + Assert.Equal(expected, exception.Failure); + Assert.Equal((int)status, exception.StatusCode); } [Fact] diff --git a/SecRandom.Core.Tests/ControlPlaneClientTests.cs b/SecRandom.Core.Tests/ControlPlaneClientTests.cs deleted file mode 100644 index 7c8bcfbff..000000000 --- a/SecRandom.Core.Tests/ControlPlaneClientTests.cs +++ /dev/null @@ -1,618 +0,0 @@ -using System.Net; -using System.Text; -using System.Text.Json; -using Microsoft.Extensions.Logging.Abstractions; -using SecRandom.Services.ControlPlane; -using SecRandom.Shared.Models.ControlPlane; - -namespace SecRandom.Core.Tests; - -/// -/// 手机端控制面客户端:解析、错误码映射、轮询到终态、超时与取消。 -/// -/// -/// -/// 全部走假发送器,一个字节都不出网。控制面的服务端鉴权还在开发中, -/// 单测如果打真实地址,跑一次 CI 就是一次误伤生产(而且必然失败)。 -/// -/// -/// 「401 刷新一次」在本客户端里的含义是:**刷新这件事不属于客户端**—— -/// 它把请求交给 (生产实现是 -/// SectlAuthService.SendAuthorizedAsync,刷新令牌在那里单飞轮换), -/// 因此客户端对一次调用只调用发送器一次,401 穿过来时按未授权上报而不是自己重试。 -/// 自己再写一套重试,会与一次性刷新令牌的轮换打架。 -/// -/// -public sealed class ControlPlaneClientTests -{ - private const string GroupId = "group 1"; - private const string NodeId = "node/2"; - - /// 线上实测的响应体(同一账号在控制台里能看到的那个组)。 - private const string ProductionGroupsBody = """ - [{"group_id":"grp_01ab30b332e6","name":"高三教学楼","owner_user_id":"69c78f81003173a586ca","owner_display_name":"黎泽懿_Aionflux","created_at":"2026-10-04T11:45:05.014+00:00","role":"owner"}] - """; - - // ---------------------------------------------------------------- 线上故障的回归点 - - [Fact] - public async Task 生产响应体必须解析出组id名字与角色() - { - // 线上"手机拿不到组"的排查,必须能在真实响应体上复现或排除。 - var sender = new FakeSender().Respond(HttpStatusCode.OK, ProductionGroupsBody); - var client = CreateClient(sender, out _); - - var group = Assert.Single(await client.GetGroupsAsync()); - - Assert.Equal("grp_01ab30b332e6", group.GroupId); - Assert.Equal("高三教学楼", group.Name); - Assert.Equal("owner", group.Role); - Assert.Equal("黎泽懿_Aionflux", group.OwnerDisplayName); - } - - [Fact] - public async Task 生产响应里的owner必须被当成有权限的角色() - { - var sender = new FakeSender().Respond(HttpStatusCode.OK, ProductionGroupsBody); - var client = CreateClient(sender, out _); - - var group = Assert.Single(await client.GetGroupsAsync()); - - // 服务端返回的角色就是 owner。只认 admin/operator 的话,组所有者本人会被判成"权限不足"。 - Assert.Equal(2, group.RoleRank); - Assert.True(group.IsAdmin); - Assert.True(group.IsOperator); - Assert.True(group.CanReadRoster); - Assert.True(group.CanOperateNodes); - Assert.False(group.IsKnownInsufficientRole); - } - - [Theory] - [InlineData("owner", true, true)] - [InlineData("admin", true, true)] - [InlineData("operator", false, true)] - [InlineData("viewer", false, false)] - [InlineData("readonly", false, false)] - // 不认识的角色不拦:拦错了合法账号就用不了,越权时服务端照样会回 403。 - [InlineData("supervisor", true, true)] - [InlineData(null, true, true)] - public void 角色等级决定能不能读名单与下发命令(string? role, bool canReadRoster, bool canOperate) - { - var group = new GroupDto { GroupId = "g1", Role = role }; - - Assert.Equal(canReadRoster, group.CanReadRoster); - Assert.Equal(canOperate, group.CanOperateNodes); - } - - [Fact] - public async Task 请求必须打到生产控制面域名而不是账号接口() - { - // 线上故障就是这一条:集控控制面是**独立域名**,打到账号/云存储那套接口会拿 404, - // 页面再把它显示成"没有组/没有设备",于是看起来像账号不在任何组里。 - Assert.Equal("https://sectl.cn", ControlPlaneClient.DefaultBaseUrl); - Assert.DoesNotContain("appwrite", ControlPlaneClient.DefaultBaseUrl, StringComparison.OrdinalIgnoreCase); - Assert.DoesNotContain("localhost", ControlPlaneClient.DefaultBaseUrl, StringComparison.OrdinalIgnoreCase); - Assert.DoesNotContain("127.0.0.1", ControlPlaneClient.DefaultBaseUrl, StringComparison.Ordinal); - - var sender = new FakeSender().Respond(HttpStatusCode.OK, "[]"); - var client = new ControlPlaneClient(sender, NullLogger.Instance); - await client.GetGroupsAsync(); - - var request = Assert.Single(sender.Requests); - Assert.Equal(HttpMethod.Get, request.Method); - Assert.Equal("https://sectl.cn/v1/groups", request.Uri.AbsoluteUri); - } - - [Fact] - public void 网页控制台地址由基址拼上控制台路由() - { - // v4.1 起控制台是主站 SPA 的一个页面:只打开基址会落到官网首页。 - Assert.Equal("https://sectl.cn/dashboard/control", ControlPlaneClient.ConsoleUrl(null)); - Assert.Equal("https://sectl.cn/dashboard/control", ControlPlaneClient.ConsoleUrl(ControlPlaneClient.DefaultBaseUrl)); - Assert.Equal("https://sectl.cn/dashboard/control", ControlPlaneClient.ConsoleUrl("https://sectl.cn/")); - Assert.Equal( - "https://cp.example.com/panel/dashboard/control", - ControlPlaneClient.ConsoleUrl("https://cp.example.com/panel/")); - } - - [Fact] - public void 旧默认域名只按主机名判定() - { - Assert.True(ControlPlaneClient.IsLegacyDefaultBaseUrl("https://secrandom-control.sectl.cn")); - Assert.True(ControlPlaneClient.IsLegacyDefaultBaseUrl("https://SECRANDOM-CONTROL.sectl.cn/panel/")); - Assert.True(ControlPlaneClient.IsLegacyDefaultBaseUrl("http://secrandom-control.sectl.cn")); - Assert.False(ControlPlaneClient.IsLegacyDefaultBaseUrl("https://sectl.cn")); - Assert.False(ControlPlaneClient.IsLegacyDefaultBaseUrl("not a url")); - Assert.False(ControlPlaneClient.IsLegacyDefaultBaseUrl(null)); - } - - [Fact] - public async Task 按组拉节点的地址是协议约定的那一条() - { - var sender = new FakeSender().Respond(HttpStatusCode.OK, "[]"); - var client = new ControlPlaneClient(sender, NullLogger.Instance); - - await client.GetNodesAsync("grp_01ab30b332e6"); - - var request = Assert.Single(sender.Requests); - Assert.Equal( - "https://sectl.cn/v1/groups/grp_01ab30b332e6/nodes", - request.Uri.AbsoluteUri); - } - - [Fact] - public async Task 失败时异常必须带上真正打出去的地址与服务端错误码() - { - // 排查"某个请求 404"时,第一件要知道的就是打到了哪个 URL。 - var sender = new FakeSender().Respond(HttpStatusCode.NotFound, """{ "error": "not_found" }"""); - var client = CreateClient(sender, out _); - - var exception = await Assert.ThrowsAsync(() => client.GetGroupsAsync()); - - Assert.Equal("not_found", exception.Code); - Assert.Equal(ControlPlaneErrorKind.NotFound, exception.Kind); - Assert.Equal("https://control.example/v1/groups", exception.RequestUri); - } - - [Fact] - public async Task 未登录时归类成需要登录而不是未知错误() - { - // 授权边界在没有登录时抛 InvalidOperationException;不归类的话界面只会显示 - // "出错:SECTL 账号未登录。",既不像"去登录"也不像"凭据失效"。 - var sender = new FakeSender { ThrowOnSend = new InvalidOperationException("SECTL 账号未登录。") }; - var client = CreateClient(sender, out _); - - var exception = await Assert.ThrowsAsync(() => client.GetGroupsAsync()); - - Assert.Equal("not_signed_in", exception.Code); - Assert.Equal(ControlPlaneErrorKind.Unauthorized, exception.Kind); - } - - // ---------------------------------------------------------------- 抽取回执(线上真实形状) - - /// 设备侧 command.result.detail 的真实形状(点名 1 人,名单「测试 1」)。 - private const string ProductionDrawResultDetail = - """{ "target": "roll_call", "list_name": "测试 1", "count": 1, "drawn": [ { "id": "12", "name": "学生12" } ] }"""; - - [Fact] - public async Task 真实抽取回执能解析出抽到的人() - { - // 线上"点名明明抽成功了、手机却说没有符合条件的人",第一个要排除的就是回执解析。 - var sender = new FakeSender().Respond(HttpStatusCode.OK, $$""" - { "command_id": "cmd_1", "capability": "draw.trigger", "status": "completed", - "result_detail": {{ProductionDrawResultDetail}} } - """); - var client = CreateClient(sender, out _); - - var command = await client.GetCommandAsync("g1", "cmd_1"); - - Assert.True(command.IsSucceeded); - var member = Assert.Single(command.DrawnMembers()); - Assert.Equal("12", member.Id); - Assert.Equal("学生12", member.Name); - Assert.Equal("学生12", member.DisplayLabel); - Assert.Equal("测试 1", command.ResultListName); - Assert.Equal(1, command.ResultCount); - } - - [Fact] - public async Task 回执里缺id或姓名时该键不写也能解析() - { - var sender = new FakeSender().Respond(HttpStatusCode.OK, """ - { "command_id": "cmd_1", "status": "completed", - "result_detail": { "target": "roll_call", "count": 2, "drawn": [ { "name": "学生12" }, { "id": "13" } ] } } - """); - var client = CreateClient(sender, out _); - - var drawn = (await client.GetCommandAsync("g1", "cmd_1")).DrawnMembers(); - - Assert.Equal(2, drawn.Count); - Assert.Null(drawn[0].Id); - Assert.Equal("学生12", drawn[0].DisplayLabel); - Assert.Equal("13", drawn[1].DisplayLabel); - } - - [Fact] - public async Task 回执被当字符串存或在别的字段里时仍然能解析() - { - // 服务端把 detail 落成 JSON 文本、或落在 result_payload 里,都不该让"抽到了谁"消失。 - var escaped = ProductionDrawResultDetail.Replace("\"", "\\\""); - var asString = new FakeSender().Respond(HttpStatusCode.OK, $$""" - { "command_id": "cmd_1", "status": "completed", "result_detail": "{{escaped}}" } - """); - var payloadInstead = new FakeSender().Respond(HttpStatusCode.OK, $$""" - { "command_id": "cmd_1", "status": "completed", "result_payload": {{ProductionDrawResultDetail}} } - """); - - var fromString = (await CreateClient(asString, out _).GetCommandAsync("g1", "cmd_1")).DrawnMembers(); - var fromPayload = (await CreateClient(payloadInstead, out _).GetCommandAsync("g1", "cmd_1")).DrawnMembers(); - - Assert.Equal("学生12", Assert.Single(fromString).Name); - Assert.Equal("学生12", Assert.Single(fromPayload).Name); - } - - [Fact] - public async Task 成功但没有成员的回执不会假装成没有符合条件的理由() - { - var sender = new FakeSender().Respond(HttpStatusCode.OK, """ - { "command_id": "cmd_1", "status": "completed", "result_detail": { "target": "roll_call", "count": 0 } } - """); - var client = CreateClient(sender, out _); - - var command = await client.GetCommandAsync("g1", "cmd_1"); - - Assert.True(command.IsSucceeded); - Assert.Empty(command.DrawnMembers()); - // 这是"客户端没读懂回执",不是"没人可抽"——两种文案由 DescribeDrawResult 分开。 - Assert.Equal( - SecRandom.Langs.Mobile.Resources.RD_ResultUnreadable, - ControlPlaneMessages.DescribeDrawResult(command)); - } - - // ---------------------------------------------------------------- 解析 - - [Fact] - public async Task 组与节点按snake_case解析且忽略未知字段() - { - var sender = new FakeSender() - .Respond(HttpStatusCode.OK, """ - [ { "group_id": "g1", "name": "高一", "role": "admin", - "owner_user_id": "u1", "member_count": 3, "future_field": true }, - { "group_id": "g2", "role": "operator" } ] - """); - - var client = CreateClient(sender, out _); - var groups = await client.GetGroupsAsync(); - - Assert.Equal(2, groups.Count); - Assert.Equal("g1", groups[0].GroupId); - Assert.Equal("高一", groups[0].DisplayLabel); - Assert.True(groups[0].IsAdmin); - Assert.True(groups[0].CanReadRoster); - Assert.Equal(3, groups[0].MemberCount); - - // 缺 name 时退回 group_id:界面上不该出现空白标签。 - Assert.Equal("g2", groups[1].DisplayLabel); - Assert.True(groups[1].IsOperator); - Assert.False(groups[1].CanReadRoster); - } - - [Fact] - public async Task 节点的能力离线与锁定状态被投影成判断() - { - var sender = new FakeSender().Respond(HttpStatusCode.OK, """ - [ { "node_id": "n1", "platform": "windows", "version": "v3.0.0", - "capabilities": [ "draw.trigger", "roster.read" ], "local_remote_allowed": true, - "display_name": "高一(1)班讲台", "online": false, "draw_locked": true } ] - """); - - var client = CreateClient(sender, out _); - var nodes = await client.GetNodesAsync("g1"); - - var node = Assert.Single(nodes); - Assert.Equal("高一(1)班讲台", node.DisplayLabel); - Assert.True(node.Supports("draw.trigger")); - Assert.False(node.Supports("Draw.Trigger")); - Assert.False(node.IsOnline); - Assert.True(node.IsDrawLocked); - Assert.True(node.IsLocalRemoteAllowed); - } - - [Fact] - public async Task 命令回执解析出抽到了谁() - { - var sender = new FakeSender().Respond(HttpStatusCode.OK, """ - { "command_id": "cmd_1", "capability": "draw.trigger", "status": "succeeded", - "result_detail": { "target": "roll_call", "list_name": "高一(1)班", "count": 2, - "drawn": [ { "id": "01", "name": "张三" }, { "name": "李四" } ] } } - """); - - var client = CreateClient(sender, out _); - var command = await client.GetCommandAsync("g1", "cmd_1"); - - Assert.True(command.IsTerminal); - Assert.True(command.IsSucceeded); - Assert.Equal("高一(1)班", command.ResultListName); - Assert.Equal(2, command.ResultCount); - - var drawn = command.DrawnMembers(); - Assert.Equal(2, drawn.Count); - Assert.Equal("张三", drawn[0].DisplayLabel); - Assert.Equal("01", drawn[0].SecondaryLabel); - - // 只有姓名时界面显示姓名,没有"次要标签"可显示。 - Assert.Equal("李四", drawn[1].DisplayLabel); - Assert.Null(drawn[1].SecondaryLabel); - } - - [Fact] - public async Task 中止状态与未完成状态分别判定() - { - var sender = new FakeSender() - .Respond(HttpStatusCode.OK, """{ "command_id": "c1", "status": "pending" }""") - .Respond(HttpStatusCode.OK, """{ "command_id": "c2", "status": "expired" }""") - .Respond(HttpStatusCode.OK, """{ "command_id": "c3", "status": "weird_new_state" }"""); - - var client = CreateClient(sender, out _); - - var pending = await client.GetCommandAsync("g1", "c1"); - var expired = await client.GetCommandAsync("g1", "c2"); - var unknown = await client.GetCommandAsync("g1", "c3"); - - Assert.False(pending.IsTerminal); - Assert.True(expired.IsTerminal); - Assert.False(expired.IsSucceeded); - // 没见过的状态当作"还要等":轮到终态就停,没轮到就继续等。 - Assert.False(unknown.IsTerminal); - } - - [Fact] - public async Task 失败命令的原因码与字段被拆出来() - { - var sender = new FakeSender().Respond(HttpStatusCode.OK, """ - { "command_id": "cmd_2", "status": "failed", - "result_detail": { "reason": "invalid_value:gender:not_in_list", "field": "gender", "why": "not_in_list" } } - """); - - var client = CreateClient(sender, out _); - var command = await client.GetCommandAsync("g1", "cmd_2"); - - Assert.True(command.IsTerminal); - Assert.False(command.IsSucceeded); - Assert.Equal("invalid_value:gender:not_in_list", command.FailureCode); - Assert.Equal("gender", command.FailureField); - Assert.Equal("not_in_list", command.FailureWhy); - } - - // ---------------------------------------------------------------- 错误映射 - - [Theory] - [InlineData(HttpStatusCode.Unauthorized, "unauthorized", ControlPlaneErrorKind.Unauthorized)] - [InlineData(HttpStatusCode.Forbidden, "insufficient_role", ControlPlaneErrorKind.Forbidden)] - [InlineData(HttpStatusCode.NotFound, "node_not_found", ControlPlaneErrorKind.NotFound)] - [InlineData(HttpStatusCode.TooManyRequests, "rate_limited", ControlPlaneErrorKind.RateLimited)] - [InlineData(HttpStatusCode.InternalServerError, "internal_error", ControlPlaneErrorKind.ServerError)] - public async Task 服务端错误码映射成强类型错误( - HttpStatusCode status, - string code, - ControlPlaneErrorKind expectedKind) - { - var sender = new FakeSender().Respond(status, $$"""{ "error": "{{code}}", "error_description": "说明" }"""); - var client = CreateClient(sender, out _); - - var exception = await Assert.ThrowsAsync(() => client.GetGroupsAsync()); - - Assert.Equal(code, exception.Code); - Assert.Equal(expectedKind, exception.Kind); - Assert.Equal((int)status, exception.StatusCode); - } - - [Fact] - public async Task 未知错误码同样保留而不是变成未知错误() - { - var sender = new FakeSender().Respond((HttpStatusCode)418, """{ "error": "teapot_mode" }"""); - var client = CreateClient(sender, out _); - - var exception = await Assert.ThrowsAsync(() => client.GetGroupsAsync()); - - Assert.Equal("teapot_mode", exception.Code); - Assert.Equal(ControlPlaneErrorKind.Unknown, exception.Kind); - } - - [Fact] - public async Task 没有错误体时退回状态码本身() - { - var sender = new FakeSender().Respond(HttpStatusCode.BadGateway, "bad gateway", "text/html"); - var client = CreateClient(sender, out _); - - var exception = await Assert.ThrowsAsync(() => client.GetGroupsAsync()); - - Assert.Equal("http_502", exception.Code); - Assert.Equal(ControlPlaneErrorKind.ServerError, exception.Kind); - } - - [Fact] - public async Task 未授权只经过一次授权边界而不是客户端自己重试() - { - // 刷新令牌是一次性的:客户端再发一次就是拿同一个旧令牌去撞,会把会话打成随机掉线。 - var sender = new FakeSender().Respond(HttpStatusCode.Unauthorized, """{ "error": "unauthorized" }"""); - var client = CreateClient(sender, out _); - - var exception = await Assert.ThrowsAsync(() => client.GetGroupsAsync()); - - Assert.Equal(ControlPlaneErrorKind.Unauthorized, exception.Kind); - Assert.Equal(1, sender.Calls); - } - - [Fact] - public async Task 成功响应读不懂时报响应异常而不是空列表() - { - var sender = new FakeSender().Respond(HttpStatusCode.OK, "{ not json"); - var client = CreateClient(sender, out _); - - var exception = await Assert.ThrowsAsync(() => client.GetGroupsAsync()); - - Assert.Equal(ControlPlaneErrorKind.InvalidResponse, exception.Kind); - } - - // ---------------------------------------------------------------- 轮询 - - [Fact] - public async Task 轮询到终态立刻停止() - { - var sender = new FakeSender() - .Respond(HttpStatusCode.OK, """{ "command_id": "c", "status": "pending" }""") - .Respond(HttpStatusCode.OK, """{ "command_id": "c", "status": "running" }""") - .Respond(HttpStatusCode.OK, """{ "command_id": "c", "status": "succeeded" }"""); - - var client = CreateClient(sender, out var delays); - var command = await client.PollCommandAsync("g1", "c"); - - Assert.True(command.IsSucceeded); - Assert.Equal(3, sender.Calls); - // 第三次已经是终态:不该再等一轮。 - Assert.Equal(2, delays.Count); - - // 节奏必须是 1s/2s/4s(第一轮与第二轮之间不等待就发起)。 - Assert.Equal(TimeSpan.FromSeconds(1), delays[0]); - Assert.Equal(TimeSpan.FromSeconds(2), delays[1]); - } - - [Fact] - public async Task 轮询超过总预算时报超时而不是抽取失败() - { - var sender = new FakeSender().RespondAlways(HttpStatusCode.OK, """{ "command_id": "c", "status": "pending" }"""); - // 这里用**真实**的等待:超时判定看的是真实经过的时间,用一个不等的假等待只会空转到天荒地老。 - var client = new ControlPlaneClient(sender, NullLogger.Instance, "https://control.example"); - - var exception = await Assert.ThrowsAsync(() => client.PollCommandAsync( - "g1", - "c", - new ControlPlanePollOptions([TimeSpan.FromMilliseconds(1)], TimeSpan.FromMilliseconds(20)))); - - // 超时是"设备还没回执",与"抽取失败"是两码事:手机端据此说"稍后再看"。 - Assert.Equal(ControlPlaneErrorKind.Timeout, exception.Kind); - Assert.True(sender.Calls > 1); - } - - [Fact] - public async Task 轮询可以被打断() - { - var sender = new FakeSender().RespondAlways(HttpStatusCode.OK, """{ "command_id": "c", "status": "pending" }"""); - var client = new ControlPlaneClient(sender, NullLogger.Instance, "https://control.example"); - - using var cancellation = new CancellationTokenSource(); - await cancellation.CancelAsync(); - - await Assert.ThrowsAnyAsync(() => client.PollCommandAsync( - "g1", - "c", - new ControlPlanePollOptions([TimeSpan.FromMilliseconds(1)], TimeSpan.FromMinutes(1)), - cancellation.Token)); - } - - // ---------------------------------------------------------------- 请求形状 - - [Fact] - public async Task 提交命令的方法地址与请求体都是协议约定的形状() - { - var sender = new FakeSender().Respond(HttpStatusCode.Accepted, """{ "command_id": "cmd_9", "status": "pending" }"""); - var client = CreateClient(sender, out _); - - var command = await client.SubmitCommandAsync( - GroupId, - NodeId, - new ControlPlaneCommandRequest - { - Capability = "draw.trigger", - Payload = JsonDocument.Parse("""{ "target": "roll_call", "count": 2 }""").RootElement.Clone() - }); - - Assert.Equal("cmd_9", command.CommandId); - - var request = Assert.Single(sender.Requests); - Assert.Equal(HttpMethod.Post, request.Method); - Assert.Equal("control.example", request.Uri.Host); - // id 里的空格与斜杠必须转义,否则会拼出另一条路由(大小写不敏感:Uri 自己会规范化十六进制)。 - Assert.Contains("group%201", request.Uri.AbsoluteUri, StringComparison.OrdinalIgnoreCase); - Assert.Contains("node%2F2", request.Uri.AbsoluteUri, StringComparison.OrdinalIgnoreCase); - Assert.EndsWith("/commands", request.Uri.AbsoluteUri, StringComparison.Ordinal); - - using var body = JsonDocument.Parse(request.Body); - Assert.Equal("draw.trigger", body.RootElement.GetProperty("capability").GetString()); - Assert.Equal("action", body.RootElement.GetProperty("kind").GetString()); - Assert.Equal("roll_call", body.RootElement.GetProperty("payload").GetProperty("target").GetString()); - } - - [Fact] - public async Task 下命令拿到非命令载荷时说清楚而不是给个空id() - { - // 期望状态那类响应(没有 command_id)如果被当成命令,调用方会拿着空 id 去轮询。 - var sender = new FakeSender().Respond(HttpStatusCode.OK, """{ "applied_revision": 12 }"""); - var client = CreateClient(sender, out _); - - var exception = await Assert.ThrowsAsync(() => client.SubmitCommandAsync( - "g1", - "n1", - new ControlPlaneCommandRequest { Capability = "draw.trigger" })); - - Assert.Equal(ControlPlaneErrorKind.InvalidResponse, exception.Kind); - } - - private static ControlPlaneClient CreateClient(FakeSender sender, out List delays) - { - var recorded = new List(); - delays = recorded; - - return new ControlPlaneClient( - sender, - NullLogger.Instance, - "https://control.example/", - (wait, _) => - { - recorded.Add(wait); - return Task.CompletedTask; - }); - } - - private sealed record SentRequest(HttpMethod Method, Uri Uri, string Body); - - private sealed class FakeSender : IAuthorizedApiSender - { - private readonly Queue> _responses = new(); - private Func? _always; - - public List Requests { get; } = []; - - public int Calls { get; private set; } - - /// 让发送器直接抛异常(模拟"未登录"这类授权边界失败)。 - public Exception? ThrowOnSend { get; init; } - - public FakeSender Respond(HttpStatusCode status, string body, string contentType = "application/json") - { - _responses.Enqueue(() => new HttpResponseMessage(status) - { - Content = new StringContent(body, Encoding.UTF8, contentType) - }); - return this; - } - - public FakeSender RespondAlways(HttpStatusCode status, string body) - { - _always = () => new HttpResponseMessage(status) - { - Content = new StringContent(body, Encoding.UTF8, "application/json") - }; - return this; - } - - public async Task SendAuthorizedAsync( - Func createRequest, - HttpCompletionOption completionOption = HttpCompletionOption.ResponseContentRead, - CancellationToken cancellationToken = default) - { - Calls++; - - if (ThrowOnSend is { } failure) - throw failure; - - using var request = createRequest(); - var body = request.Content is null - ? string.Empty - : await request.Content.ReadAsStringAsync(cancellationToken); - - Requests.Add(new SentRequest(request.Method, request.RequestUri!, body)); - - var factory = _responses.Count > 0 - ? _responses.Dequeue() - : _always ?? throw new InvalidOperationException("测试没有为这次调用准备响应。"); - - var response = factory(); - // 生产里 HttpClient 会把请求挂到响应上,异常里的 URL 就是这么来的;假发送器要照做, - // 否则"异常带 URL"这条只有线上才成立。 - response.RequestMessage ??= request; - return response; - } - } -} diff --git a/SecRandom.Core.Tests/ControlPlaneEndpointSettingsTests.cs b/SecRandom.Core.Tests/ControlPlaneEndpointSettingsTests.cs index 590873469..1a9aec504 100644 --- a/SecRandom.Core.Tests/ControlPlaneEndpointSettingsTests.cs +++ b/SecRandom.Core.Tests/ControlPlaneEndpointSettingsTests.cs @@ -1,17 +1,16 @@ -using System.Net; -using System.Text; using Microsoft.Extensions.Logging.Abstractions; using SecRandom.Services.ControlPlane; namespace SecRandom.Core.Tests; /// -/// 控制面(集控 REST)基址:校验/规范化、落盘与回落,以及客户端实际打出去的地址。 +/// 控制面(集控 REST)基址:校验/规范化、落盘与回落。 /// /// /// -/// 这一组守的是一条**安全边界**:控制面地址每次请求都会带上本账号的 SECTL access token, -/// 因此它既不能明文出网(只允许回环),也不能因为一次设置导入而被改掉——它不在 +/// 这一组守的是一条**安全边界**:这个地址曾经是账号控制台的基址,而账号控制台的每个请求 +/// 都会带上本账号的 SECTL access token;现在账号控制台固定打官方域名,这里只剩配对码 +/// 节点接入与设置页展示使用的地址,仍然不允许明文出网(只允许回环)。它不在 /// settings.json 里,而在 data/config/control-plane/endpoint.json。 /// /// @@ -77,7 +76,7 @@ private FileControlPlaneEndpointStore CreateStore() => { var store = CreateStore(); - Assert.Equal(ControlPlaneClient.DefaultBaseUrl, store.Current); + Assert.Equal(ControlPlaneDefaults.DefaultBaseUrl, store.Current); Assert.False(store.IsCustom); } @@ -120,9 +119,9 @@ private FileControlPlaneEndpointStore CreateStore() => store.ResetToDefault(); - Assert.Equal(ControlPlaneClient.DefaultBaseUrl, store.Current); + Assert.Equal(ControlPlaneDefaults.DefaultBaseUrl, store.Current); Assert.False(store.IsCustom); - Assert.Equal(ControlPlaneClient.DefaultBaseUrl, CreateStore().Current); + Assert.Equal(ControlPlaneDefaults.DefaultBaseUrl, CreateStore().Current); } [Fact] @@ -131,12 +130,12 @@ private FileControlPlaneEndpointStore CreateStore() => var store = CreateStore(); Assert.True(store.TryUpdate("https://cp.example.com", out _)); - Assert.True(store.TryUpdate(ControlPlaneClient.DefaultBaseUrl + "/", out var error)); + Assert.True(store.TryUpdate(ControlPlaneDefaults.DefaultBaseUrl + "/", out var error)); Assert.Null(error); Assert.False(store.IsCustom); // 文件不会留下一条"与默认逐字相同"的自定义地址:否则"恢复默认"按钮会一直亮着。 - Assert.Equal(ControlPlaneClient.DefaultBaseUrl, CreateStore().Current); + Assert.Equal(ControlPlaneDefaults.DefaultBaseUrl, CreateStore().Current); } [Fact] @@ -150,7 +149,7 @@ private FileControlPlaneEndpointStore CreateStore() => var store = CreateStore(); - Assert.Equal(ControlPlaneClient.DefaultBaseUrl, store.Current); + Assert.Equal(ControlPlaneDefaults.DefaultBaseUrl, store.Current); Assert.False(store.IsCustom); if (File.Exists(path)) Assert.DoesNotContain("secrandom-control", File.ReadAllText(path), StringComparison.OrdinalIgnoreCase); @@ -166,7 +165,7 @@ private FileControlPlaneEndpointStore CreateStore() => Assert.Null(error); Assert.False(store.IsCustom); - Assert.Equal(ControlPlaneClient.DefaultBaseUrl, CreateStore().Current); + Assert.Equal(ControlPlaneDefaults.DefaultBaseUrl, CreateStore().Current); } [Fact] @@ -190,7 +189,7 @@ private FileControlPlaneEndpointStore CreateStore() => var store = CreateStore(); - Assert.Equal(ControlPlaneClient.DefaultBaseUrl, store.Current); + Assert.Equal(ControlPlaneDefaults.DefaultBaseUrl, store.Current); Assert.False(store.IsCustom); } @@ -205,75 +204,10 @@ private FileControlPlaneEndpointStore CreateStore() => var store = CreateStore(); - Assert.Equal(ControlPlaneClient.DefaultBaseUrl, store.Current); + Assert.Equal(ControlPlaneDefaults.DefaultBaseUrl, store.Current); } - // ---------------------------------------------------------------- 客户端真的打这个地址 - - [Fact] - public async Task 配置过的地址会用在请求上() - { - var store = CreateStore(); - Assert.True(store.TryUpdate("https://cp.example.com/panel", out _)); - - var sender = new RecordingSender(); - var client = new ControlPlaneClient( - sender, - NullLogger.Instance, - endpointStore: store); - - await client.GetGroupsAsync(); - - Assert.Equal("https://cp.example.com/panel/v1/groups", Assert.Single(sender.Requests).AbsoluteUri); - } - - [Fact] - public async Task 没配置过时仍然打生产控制面域名() - { - var sender = new RecordingSender(); - var client = new ControlPlaneClient( - sender, - NullLogger.Instance, - endpointStore: CreateStore()); - - await client.GetGroupsAsync(); - - Assert.Equal("https://sectl.cn/v1/groups", Assert.Single(sender.Requests).AbsoluteUri); - } - - [Fact] - public async Task 地址改完之后不需要重建客户端() - { - // 地址是可以在设置里改的;改完还要重启才生效,等于这个设置是假的。 - var store = CreateStore(); - var sender = new RecordingSender(); - var client = new ControlPlaneClient( - sender, - NullLogger.Instance, - endpointStore: store); - - Assert.True(store.TryUpdate("https://cp.example.com", out _)); - await client.GetGroupsAsync(); - - Assert.Equal("https://cp.example.com/v1/groups", Assert.Single(sender.Requests).AbsoluteUri); - } - - private sealed class RecordingSender : IAuthorizedApiSender - { - public List Requests { get; } = []; - - public Task SendAuthorizedAsync( - Func createRequest, - HttpCompletionOption completionOption = HttpCompletionOption.ResponseContentRead, - CancellationToken cancellationToken = default) - { - using var request = createRequest(); - Requests.Add(request.RequestUri!); - - return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent("[]", Encoding.UTF8, "application/json") - }); - } - } + // 账号控制台(ControlCenterClient)固定打官方 https://sectl.cn/control/api, + // 不再读取这个基址:JWT 不允许被自定义地址带走,所以原来的「客户端真的打这个地址」 + // 三个断言随 v1 控制面一起退出;这个存储只剩配对码节点接入与设置页展示的地址。 } diff --git a/SecRandom.Core.Tests/ControlSettingsCatalogTests.cs b/SecRandom.Core.Tests/ControlSettingsCatalogTests.cs index 7089f7369..a3e5a9671 100644 --- a/SecRandom.Core.Tests/ControlSettingsCatalogTests.cs +++ b/SecRandom.Core.Tests/ControlSettingsCatalogTests.cs @@ -440,6 +440,10 @@ static ControlSettingField VolumeFor(string? locale) => "general.basic.guide_completed", "general.basic.accepted_privacy_policy_version", "general.proof_retention.retention_days", + // 收纳手柄的文字/图标内容是本机外观,远程改它只会让手柄变样或指向本机不存在的图片。 + "floating_window.stick_to_edge_display_text", + "floating_window.stick_to_edge_display_icon_glyph", + "floating_window.stick_to_edge_display_icon_image", // 默认记录组:远程改它会让下一节课的抽取范围在无人操作时静默变化。 "roll_call.history_group", "quick_draw.history_group", diff --git a/SecRandom.Core.Tests/ControlSettingsStatusTests.cs b/SecRandom.Core.Tests/ControlSettingsStatusTests.cs index 7902ef847..6d22c6069 100644 --- a/SecRandom.Core.Tests/ControlSettingsStatusTests.cs +++ b/SecRandom.Core.Tests/ControlSettingsStatusTests.cs @@ -220,7 +220,7 @@ public void Update(Func mutate) private sealed class FakeEndpointStore : IControlPlaneEndpointStore { - private string _current = ControlPlaneClient.DefaultBaseUrl; + private string _current = ControlPlaneDefaults.DefaultBaseUrl; public string Current => _current; @@ -245,7 +245,7 @@ public bool TryUpdate(string? endpoint, out string? error) public void ResetToDefault() { - _current = ControlPlaneClient.DefaultBaseUrl; + _current = ControlPlaneDefaults.DefaultBaseUrl; IsCustom = false; Changed?.Invoke(this, _current); } diff --git a/SecRandom.Core.Tests/DataArchiveServiceTests.cs b/SecRandom.Core.Tests/DataArchiveServiceTests.cs index 0b2f39f36..993f356f8 100644 --- a/SecRandom.Core.Tests/DataArchiveServiceTests.cs +++ b/SecRandom.Core.Tests/DataArchiveServiceTests.cs @@ -93,11 +93,61 @@ public async Task ExportAllData_NeverCarriesTheSecurityDirectory() var paths = ReadManifestPaths(destination); Assert.DoesNotContain(paths, path => path.StartsWith("config/security", StringComparison.OrdinalIgnoreCase)); + } + + [Fact] + public async Task ExportAllData_CarriesTheOrchestrationSection() + { + using var provider = CreateProvider(); + provider.GetRequiredService().Save(); + var profileId = Guid.NewGuid().ToString("N"); + File.WriteAllText(Utils.GetFilePath("config", "orchestration", profileId + ".json"), "{}"); + File.WriteAllText(Utils.GetFilePath("config", "orchestration", "runtime", profileId + ".json"), "{}"); + + var archive = provider.GetRequiredService(); + var destination = Path.Combine(_exportDirectory, "all-data-orchestration.zip"); + await archive.ExportAllDataAsync(destination, TestContext.Current.CancellationToken); + + var paths = ReadManifestPaths(destination); + Assert.Contains($"config/orchestration/{profileId}.json", paths); + Assert.Contains($"config/orchestration/runtime/{profileId}.json", paths); + } + + [Fact] + public async Task ImportAllData_RestoresTheOrchestrationSection() + { + using var provider = CreateProvider(); + provider.GetRequiredService().Save(); + var profileId = Guid.NewGuid().ToString("N"); + var profilePath = Utils.GetFilePath("config", "orchestration", profileId + ".json"); + File.WriteAllText(profilePath, "{}"); + + var archive = provider.GetRequiredService(); + var destination = Path.Combine(_exportDirectory, "all-data-orchestration-import.zip"); + await archive.ExportAllDataAsync(destination, TestContext.Current.CancellationToken); + StampProducerVersion(destination, TestV3ProducerVersion); + + // 编排段在 config/ 下是唯一按目录提交的根:折叠成 settings.json 会让整段顺序名单在导入时消失。 + Directory.Delete(Path.GetDirectoryName(profilePath)!, true); + await archive.ImportAllDataAsync(destination, TestContext.Current.CancellationToken); + + Assert.True(File.Exists(profilePath)); + } + + [Fact] + public async Task ImportAllData_RejectsACorruptOrchestrationFileBeforeTouchingData() + { + using var provider = CreateProvider(); + provider.GetRequiredService().Save(); + var archive = provider.GetRequiredService(); + var destination = Path.Combine(_exportDirectory, "all-data-orchestration-corrupt.zip"); + await archive.ExportAllDataAsync(destination, TestContext.Current.CancellationToken); + StampProducerVersion(destination, TestV3ProducerVersion); + AddArchiveEntry(destination, "config/orchestration/broken.json", Encoding.UTF8.GetBytes("{ broken")); - // 云备份的上限里同样没有这个目录 - var cloudRoots = DataArchiveService.ResolveCloudBackupRoots( - provider.GetRequiredService().Data.General.Backup); - Assert.DoesNotContain(cloudRoots, root => root.StartsWith("config/security", StringComparison.OrdinalIgnoreCase)); + await Assert.ThrowsAnyAsync(() => + archive.ImportAllDataAsync(destination, TestContext.Current.CancellationToken)); + Assert.False(File.Exists(Utils.GetFilePath("config", "orchestration", "broken.json"))); } [Fact] @@ -143,7 +193,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 +559,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 +775,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/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.Tests/DrawCommitCoordinatorTests.cs b/SecRandom.Core.Tests/DrawCommitCoordinatorTests.cs index 4453a93c2..45eb92075 100644 --- a/SecRandom.Core.Tests/DrawCommitCoordinatorTests.cs +++ b/SecRandom.Core.Tests/DrawCommitCoordinatorTests.cs @@ -136,7 +136,8 @@ public async Task ProtocolRouter_GroupsHistoryEntriesBySharedDrawRoundId() null!, new ProfileQueryService(provider.GetRequiredService()), null!, - provider.GetRequiredService()); + provider.GetRequiredService(), + new PageRouteResolver(provider.GetRequiredService())); var response = await router.HandleIpcAsync( new IpcRequestEnvelope(1, "request", new IpcRequestPayload($"data/roll_call_history?name={listName}")), diff --git a/SecRandom.Core.Tests/DrawModeSelectionTests.cs b/SecRandom.Core.Tests/DrawModeSelectionTests.cs new file mode 100644 index 000000000..2203ebec9 --- /dev/null +++ b/SecRandom.Core.Tests/DrawModeSelectionTests.cs @@ -0,0 +1,195 @@ +using SecRandom.Core.Enums.Configs; +using SecRandom.Core.Models.SubConfigs.Picking; +using SecRandom.Core.Services.Draw; +using Xunit; + +namespace SecRandom.Core.Tests; + +/// +/// 编排抽取是「抽取方式」而不是「抽取模式」:进入编排时先记住通道原来的重复策略,退出时还回去, +/// 否则一次编排就会把用户的半重复档位静默压成不重复。 +/// +public class DrawModeSelectionTests +{ + [Fact] + public void EnteringOrchestrationRemembersTheRepeatPolicy() + { + var settings = new RollCallSettingsConfig { DrawMode = DrawMode.HalfRepeat, HalfRepeat = 5 }; + + DrawModeSelection.SelectOrchestrated(settings); + + Assert.Equal(DrawMode.Orchestrated, settings.DrawMode); + Assert.Equal(DrawMode.HalfRepeat, settings.SampledDrawMode); + + DrawModeSelection.LeaveOrchestrated(settings); + + Assert.Equal(DrawMode.HalfRepeat, settings.DrawMode); + Assert.Equal(5, settings.HalfRepeat); + } + + [Fact] + public void ReSelectingOrchestrationKeepsTheFirstRecordedPolicy() + { + var settings = new LotterySettingsConfig { DrawMode = DrawMode.Repeat }; + + DrawModeSelection.SelectOrchestrated(settings); + DrawModeSelection.SelectOrchestrated(settings); + + Assert.Equal(DrawMode.Orchestrated, settings.DrawMode); + Assert.Equal(DrawMode.Repeat, settings.SampledDrawMode); + } + + [Fact] + public void LeavingOrchestrationNeverRestoresOrchestration() + { + var settings = new QuickDrawSettingsConfig + { + DrawMode = DrawMode.Orchestrated, + SampledDrawMode = DrawMode.Orchestrated + }; + + DrawModeSelection.LeaveOrchestrated(settings); + + Assert.Equal(DrawMode.NoRepeat, settings.DrawMode); + Assert.Equal(DrawMode.Orchestrated, settings.SampledDrawMode); + } + + [Fact] + public void LeavingASampledChannelIsANoOp() + { + var settings = new RollCallSettingsConfig + { + DrawMode = DrawMode.NoRepeat, + SampledDrawMode = DrawMode.HalfRepeat + }; + + DrawModeSelection.LeaveOrchestrated(settings); + + Assert.Equal(DrawMode.NoRepeat, settings.DrawMode); + Assert.Equal(DrawMode.HalfRepeat, settings.SampledDrawMode); + } + + [Fact] + public void IsOrchestratedOnlyMatchesTheOrchestratedValue() + { + Assert.True(DrawModeSelection.IsOrchestrated(DrawMode.Orchestrated)); + Assert.False(DrawModeSelection.IsOrchestrated(DrawMode.Repeat)); + Assert.False(DrawModeSelection.IsOrchestrated(DrawMode.NoRepeat)); + Assert.False(DrawModeSelection.IsOrchestrated(DrawMode.HalfRepeat)); + } + + /// + /// 「抽取模式」下拉框读的就是这个值:它必须永远是 0..2 的重复策略,否则三个选项的 + /// 下拉框会把越界索引压成 -1 再 TwoWay 写回配置,既清空下拉又丢掉编排状态。 + /// + [Theory] + [InlineData(DrawMode.Repeat, DrawMode.Repeat)] + [InlineData(DrawMode.NoRepeat, DrawMode.NoRepeat)] + [InlineData(DrawMode.HalfRepeat, DrawMode.HalfRepeat)] + [InlineData(DrawMode.Orchestrated, DrawMode.Orchestrated)] + public void ResolveRepeatPolicyIsAlwaysARepeatPolicy(DrawMode effectiveMode, DrawMode sampled) + { + var settings = new RollCallSettingsConfig { DrawMode = effectiveMode, SampledDrawMode = sampled }; + + Assert.NotEqual(DrawMode.Orchestrated, DrawModeSelection.ResolveRepeatPolicy(settings)); + } + + [Theory] + [InlineData(DrawMode.Repeat)] + [InlineData(DrawMode.NoRepeat)] + [InlineData(DrawMode.HalfRepeat)] + public void SamplingChannelShowsItsEffectiveRepeatPolicy(DrawMode effectiveMode) + { + var settings = new QuickDrawSettingsConfig + { + DrawMode = effectiveMode, + SampledDrawMode = DrawMode.HalfRepeat + }; + + Assert.Equal(effectiveMode, DrawModeSelection.ResolveRepeatPolicy(settings)); + } + + [Fact] + public void OrchestratedChannelShowsTheRememberedRepeatPolicy() + { + var settings = new LotterySettingsConfig + { + DrawMode = DrawMode.Orchestrated, + SampledDrawMode = DrawMode.HalfRepeat + }; + + Assert.Equal(DrawMode.HalfRepeat, DrawModeSelection.ResolveRepeatPolicy(settings)); + } + + [Fact] + public void InvalidRememberedPolicyFallsBackToNoRepeat() + { + var settings = new LotterySettingsConfig + { + DrawMode = DrawMode.Orchestrated, + SampledDrawMode = DrawMode.Orchestrated + }; + + Assert.Equal(DrawMode.NoRepeat, DrawModeSelection.ResolveRepeatPolicy(settings)); + } + + [Fact] + public void ChoosingARepeatPolicyWhileSamplingChangesTheEffectiveModeToo() + { + var settings = new RollCallSettingsConfig { DrawMode = DrawMode.NoRepeat }; + + DrawModeSelection.SetRepeatPolicy(settings, DrawMode.HalfRepeat); + + Assert.Equal(DrawMode.HalfRepeat, settings.DrawMode); + Assert.Equal(DrawMode.HalfRepeat, settings.SampledDrawMode); + } + + [Fact] + public void ChoosingARepeatPolicyWhileOrchestratedOnlyRemembersIt() + { + var settings = new RollCallSettingsConfig + { + DrawMode = DrawMode.Orchestrated, + SampledDrawMode = DrawMode.Repeat + }; + + DrawModeSelection.SetRepeatPolicy(settings, DrawMode.HalfRepeat); + + Assert.Equal(DrawMode.Orchestrated, settings.DrawMode); + Assert.Equal(DrawMode.HalfRepeat, settings.SampledDrawMode); + Assert.Equal(DrawMode.HalfRepeat, DrawModeSelection.ResolveRepeatPolicy(settings)); + } + + [Fact] + public void SetRepeatPolicyRejectsOrchestration() + { + var settings = new RollCallSettingsConfig { DrawMode = DrawMode.NoRepeat }; + + DrawModeSelection.SetRepeatPolicy(settings, DrawMode.Orchestrated); + + Assert.Equal(DrawMode.NoRepeat, settings.DrawMode); + Assert.Equal(DrawMode.NoRepeat, settings.SampledDrawMode); + } + + [Fact] + public void SynchronizeFollowsTheEffectiveModeOnlyWhileSampling() + { + var sampling = new RollCallSettingsConfig + { + DrawMode = DrawMode.HalfRepeat, + SampledDrawMode = DrawMode.Repeat + }; + DrawModeSelection.SynchronizeRepeatPolicy(sampling); + Assert.Equal(DrawMode.HalfRepeat, sampling.DrawMode); + Assert.Equal(DrawMode.HalfRepeat, sampling.SampledDrawMode); + + var orchestrated = new RollCallSettingsConfig + { + DrawMode = DrawMode.Orchestrated, + SampledDrawMode = DrawMode.Repeat + }; + DrawModeSelection.SynchronizeRepeatPolicy(orchestrated); + Assert.Equal(DrawMode.Orchestrated, orchestrated.DrawMode); + Assert.Equal(DrawMode.Repeat, orchestrated.SampledDrawMode); + } +} \ No newline at end of file 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/DrawProofExportServiceTests.cs b/SecRandom.Core.Tests/DrawProofExportServiceTests.cs index b43b5c568..2a4ebf8ab 100644 --- a/SecRandom.Core.Tests/DrawProofExportServiceTests.cs +++ b/SecRandom.Core.Tests/DrawProofExportServiceTests.cs @@ -8,7 +8,7 @@ namespace SecRandom.Core.Tests; public sealed class DrawProofExportServiceTests { [Fact] - public void CreateFileName_UsesChinaStandardTimeListAndFilters() + public void CreateFileName_UsesChinaStandardTimeAndProofIdOnly() { DrawProof proof = new() { @@ -16,48 +16,13 @@ public void CreateFileName_UsesChinaStandardTimeListAndFilters() CreatedAtUtc = new DateTimeOffset(2026, 7, 14, 0, 30, 12, 345, TimeSpan.Zero) }; - var fileName = DrawProofExportService.CreateFileName( - proof, - DrawProofExportContext.ForStudents("高一:一班", "A/组", "女")); + var fileName = DrawProofExportService.CreateFileName(proof); - Assert.Equal("20260714_083012_345_高一_一班_组别=A_组_性别=女_12345678.srproof.json", fileName); + Assert.Equal("20260714_083012_345_12345678.srproof.json", fileName); } [Fact] - public void CreateFileName_UsesAllScopeWhenNoStudentFilterIsSelected() - { - DrawProof proof = new() - { - ProofId = Guid.Parse("abcdef12-1234-1234-1234-123456789abc"), - CreatedAtUtc = new DateTimeOffset(2026, 7, 14, 0, 0, 0, TimeSpan.Zero) - }; - - var fileName = DrawProofExportService.CreateFileName(proof, DrawProofExportContext.ForStudents("默认名单")); - - Assert.Contains("默认名单_全部_abcdef12", fileName); - } - - [Fact] - public void CreateFileName_UsesPrizePoolAndLotteryMode() - { - DrawProof proof = new() - { - ProofId = Guid.Parse("abcdef12-1234-1234-1234-123456789abc"), - CreatedAtUtc = new DateTimeOffset(2026, 7, 14, 0, 0, 0, TimeSpan.Zero), - AlgorithmId = VerificationWireCodec.InventoryLotteryAlgorithmId - }; - - var fileName = DrawProofExportService.CreateFileName( - proof, - DrawProofExportContext.ForPrizes("期末奖池")); - - Assert.Contains("期末奖池_按剩余数量_abcdef12", fileName); - Assert.DoesNotContain("方式=", fileName); - Assert.DoesNotContain("状态=", fileName); - } - - [Fact] - public void CreateFileName_UsesStudentAlgorithmProfile() + public void CreateFileName_CarriesNoRosterFilterOrAlgorithmText() { DrawProof proof = new() { @@ -66,54 +31,33 @@ public void CreateFileName_UsesStudentAlgorithmProfile() AlgorithmId = VerificationWireCodec.GetAlgorithmId(VerificationAlgorithmProfile.StudentRandomHalfRepeat) }; - var fileName = DrawProofExportService.CreateFileName( - proof, - DrawProofExportContext.ForStudents("默认名单")); + var fileName = DrawProofExportService.CreateFileName(proof); - Assert.Contains("默认名单_点名_随机_半重复_abcdef12", fileName); - Assert.DoesNotContain(':', fileName); - Assert.DoesNotContain(',', fileName); + // The file name is visible in every folder listing, archive, and support screenshot, so it must not say + // more than the document does: the roster name, the filter values, and the readable algorithm label used + // to leak there while the proof body stayed de-identified. + Assert.DoesNotContain("高一", fileName); + Assert.DoesNotContain("组别", fileName); + Assert.DoesNotContain("性别", fileName); + Assert.DoesNotContain("全部", fileName); + Assert.DoesNotContain("点名", fileName); Assert.DoesNotContain(':', fileName); - Assert.DoesNotContain(',', fileName); - Assert.DoesNotContain('、', fileName); - } - - [Theory] - [InlineData("secrandom-lottery-inventory-count/v3")] - [InlineData("secrandom-lottery-count-internal-rule/v3")] - [InlineData("secrandom-lottery-pan-repeat/v3")] - [InlineData("secrandom-lottery-pan-no-repeat/v3")] - [InlineData("secrandom-lottery-pan-half-repeat/v3")] - public void CreateFileName_RemovesPunctuationFromLotteryAlgorithmLabels(string algorithmId) - { - var proof = new DrawProof - { - ProofId = Guid.Parse("abcdef12-1234-1234-1234-123456789abc"), - CreatedAtUtc = new DateTimeOffset(2026, 7, 14, 0, 0, 0, TimeSpan.Zero), - AlgorithmId = algorithmId - }; - - var fileName = DrawProofExportService.CreateFileName( - proof, - DrawProofExportContext.ForPrizes("期末奖池")); - - Assert.DoesNotContain(':', fileName); - Assert.DoesNotContain(',', fileName); - Assert.DoesNotContain(':', fileName); - Assert.DoesNotContain(',', fileName); Assert.DoesNotContain('、', fileName); } [Fact] public void CreateFileName_KeepsTheFileNameWithinWindowsLimits() { - DrawProof proof = new(); - var context = new DrawProofExportContext( - new string('名', 100), - [new string('组', 100), new string('性', 100), new string('课', 100)]); + DrawProof proof = new() + { + ProofId = Guid.NewGuid(), + CreatedAtUtc = DateTimeOffset.UtcNow + }; - var fileName = DrawProofExportService.CreateFileName(proof, context); + var fileName = DrawProofExportService.CreateFileName(proof); - Assert.True(fileName.Length <= 240); + // The name no longer embeds user text, so its length is fixed regardless of the roster or the filters. + Assert.True(fileName.Length <= 64, fileName); + Assert.Matches("^[0-9]{8}_[0-9]{6}_[0-9]{3}_[0-9a-f]{8}\\.srproof\\.json$", fileName); } -} +} \ No newline at end of file diff --git a/SecRandom.Core.Tests/FairDrawAlgorithmTests.cs b/SecRandom.Core.Tests/FairDrawAlgorithmTests.cs index da1afe424..f4dbe7090 100644 --- a/SecRandom.Core.Tests/FairDrawAlgorithmTests.cs +++ b/SecRandom.Core.Tests/FairDrawAlgorithmTests.cs @@ -366,6 +366,165 @@ public void CountLotteryVerification_CanIgnoreInternalRules() Assert.Equal(0, audit.RootElement.GetProperty("internalExcludedCandidateCount").GetInt32()); } + [Fact] + public void RandomFirst_ZeroesAboveThresholdWeightsWithoutHardGate() + { + var low = new Student { Name = "Low", RecordId = Guid.NewGuid() }; + var average = new Student { Name = "Average", RecordId = Guid.NewGuid() }; + var high = new Student { Name = "High", RecordId = Guid.NewGuid() }; + var history = new StudentHistory + { + Students = + { + [low.RecordId.ToString("D")] = new History { TotalCount = 0 }, + [average.RecordId.ToString("D")] = new History { TotalCount = 2 }, + [high.RecordId.ToString("D")] = new History { TotalCount = 4 } + } + }; + var config = CreateConfig(new FairDrawSettingsConfig + { + FairDraw = true, + FairDrawGroup = false, + FairDrawGender = false, + FairDrawTime = false, + ColdStartEnabled = false, + Mode = FairDrawMode.RandomFirst + }); + var students = new List { low, average, high }; + + using var host = CreateHost(config, new TestProfileService(history, new StudentList { Students = new ObservableCollection(students) })); + var engine = CreateEngine(host); + + var weights = engine.CalculateStudentWeight(students); + Assert.Equal(1.0, weights.Single(candidate => candidate.Candidate == low).Weight, 6); + Assert.Equal(0.0, weights.Single(candidate => candidate.Candidate == average).Weight); + Assert.Equal(0.0, weights.Single(candidate => candidate.Candidate == high).Weight); + + var input = engine.CreateStudentVerificationInput(1, students, DrawSettingsType.RollCall); + using var audit = JsonDocument.Parse(input.AuditPayload); + var fairness = audit.RootElement.GetProperty("fairness"); + + Assert.False(fairness.GetProperty("averageGapProtectionApplied").GetBoolean()); + Assert.Equal(3, fairness.GetProperty("candidateCountAfterAverageGapProtection").GetInt32()); + + // Random-first keeps the whole roster in the verification payload; the ceiling shows up as exact + // zero weights instead of a shorter candidate list, which is what "no hard average gate" means. + Assert.Equal(3, input.Candidates.Count); + Assert.Single(input.Candidates.Where(candidate => candidate.WeightMicros > 0)); + Assert.Equal(0, input.Candidates.Single(candidate => candidate.RecordId == high.RecordId).WeightMicros); + Assert.Equal(0, input.Candidates.Single(candidate => candidate.RecordId == average.RecordId).WeightMicros); + } + + [Fact] + public void RandomFirst_RelaxesThresholdToKeepRequiredCountDrawable() + { + var zero = new Student { Name = "Zero", RecordId = Guid.NewGuid() }; + var first = new Student { Name = "First", RecordId = Guid.NewGuid() }; + var second = new Student { Name = "Second", RecordId = Guid.NewGuid() }; + var third = new Student { Name = "Third", RecordId = Guid.NewGuid() }; + var history = new StudentHistory + { + Students = + { + [zero.RecordId.ToString("D")] = new History { TotalCount = 0 }, + [first.RecordId.ToString("D")] = new History { TotalCount = 10 }, + [second.RecordId.ToString("D")] = new History { TotalCount = 10 }, + [third.RecordId.ToString("D")] = new History { TotalCount = 10 } + } + }; + var config = CreateConfig(new FairDrawSettingsConfig + { + FairDraw = true, + FairDrawGroup = false, + FairDrawGender = false, + FairDrawTime = false, + ColdStartEnabled = false, + Mode = FairDrawMode.RandomFirst + }); + var students = new List { zero, first, second, third }; + + using var host = CreateHost(config, new TestProfileService(history, new StudentList { Students = new ObservableCollection(students) })); + var engine = CreateEngine(host); + + var input = engine.CreateStudentVerificationInput(2, students, DrawSettingsType.RollCall); + var local = engine.DrawPreparedStudents(2, students, DrawSettingsType.RollCall); + + // The minimum is 0, so the ceiling is 2: only the zero-count member is drawable at first. Asking + // for two members relaxes the ceiling to 11, which pulls every tied 10-count member back in. + Assert.Equal(4, input.Candidates.Count); + Assert.True(local.IsSuccess); + Assert.Equal(2, local.Result.Count); + } + + /// + /// Both modes run the same tiering formula; the mode only decides which pool it measures and how many + /// candidates must stay drawable. Uniform-first measures the gated pool, random-first measures the whole + /// roster and lets the above-average members fall to exactly zero. + /// + [Fact] + public void UnifiedWeights_ShareTheSameTierFormulaAcrossModes() + { + var zero = new Student { Name = "Zero", RecordId = Guid.NewGuid() }; + var first = new Student { Name = "First", RecordId = Guid.NewGuid() }; + var second = new Student { Name = "Second", RecordId = Guid.NewGuid() }; + var third = new Student { Name = "Third", RecordId = Guid.NewGuid() }; + var history = new StudentHistory + { + Students = + { + [zero.RecordId.ToString("D")] = new History { TotalCount = 0 }, + [first.RecordId.ToString("D")] = new History { TotalCount = 1 }, + [second.RecordId.ToString("D")] = new History { TotalCount = 2 }, + [third.RecordId.ToString("D")] = new History { TotalCount = 3 } + } + }; + var students = new List { zero, first, second, third }; + + var randomConfig = CreateConfig(new FairDrawSettingsConfig + { + FairDraw = true, + FairDrawGroup = false, + FairDrawGender = false, + FairDrawTime = false, + ColdStartEnabled = false, + Mode = FairDrawMode.RandomFirst + }); + using (var randomHost = CreateHost(randomConfig, new TestProfileService(history, new StudentList { Students = new ObservableCollection(students) }))) + { + var randomEngine = CreateEngine(randomHost); + var randomWeights = randomEngine.CalculateStudentWeight(students); + + // While somebody is still at zero the lead cap is one, so only the never-drawn member is drawable. + Assert.Equal(1.0, randomWeights.Single(candidate => candidate.Candidate == zero).Weight, 6); + Assert.Equal(0.0, randomWeights.Single(candidate => candidate.Candidate == first).Weight); + Assert.Equal(0.0, randomWeights.Single(candidate => candidate.Candidate == second).Weight); + Assert.Equal(0.0, randomWeights.Single(candidate => candidate.Candidate == third).Weight); + } + + var uniformConfig = CreateConfig(new FairDrawSettingsConfig + { + FairDraw = true, + FairDrawGroup = false, + FairDrawGender = false, + FairDrawTime = false, + ColdStartEnabled = false, + Mode = FairDrawMode.UniformFirst + }); + using (var uniformHost = CreateHost(uniformConfig, new TestProfileService(history, new StudentList { Students = new ObservableCollection(students) }))) + { + var uniformEngine = CreateEngine(uniformHost); + + var gated = uniformEngine.CreateStudentVerificationInput(1, students, DrawSettingsType.RollCall); + Assert.Equal(2, gated.Candidates.Count); + Assert.DoesNotContain(gated.Candidates, candidate => candidate.RecordId == second.RecordId); + + var pool = new List { zero, first }; + var uniformWeights = uniformEngine.CalculateStudentWeight(pool); + Assert.Equal(0.666667, uniformWeights.Single(candidate => candidate.Candidate == zero).Weight, 6); + Assert.Equal(0.333333, uniformWeights.Single(candidate => candidate.Candidate == first).Weight, 6); + } + } + private static MainConfigModel CreateConfig(FairDrawSettingsConfig fairSettings) { return new MainConfigModel diff --git a/SecRandom.Core.Tests/FairDrawSettingsConfigTests.cs b/SecRandom.Core.Tests/FairDrawSettingsConfigTests.cs index f78ad5572..c12c34373 100644 --- a/SecRandom.Core.Tests/FairDrawSettingsConfigTests.cs +++ b/SecRandom.Core.Tests/FairDrawSettingsConfigTests.cs @@ -70,19 +70,19 @@ public void AverageGapProtectionIsMandatoryAndLegacyToggleIsNotPersisted() } [Fact] - public void ShareDebtWeightsUsePersonalAndEnabledDimensionDebt() + public void UnifiedWeightsZeroOutAboveTheAverageTierInRandomMode() { - var first = new Student { Name = "A", Group = "G1", Gender = "男" }; - var second = new Student { Name = "B", Group = "G2", Gender = "女" }; - var third = new Student { Name = "C", Group = "G2", Gender = "男" }; + var first = new Student { Name = "A" }; + var second = new Student { Name = "B" }; + var third = new Student { Name = "C" }; var config = BuildConfig(new FairDrawSettingsConfig { FairDraw = true, - FairDrawGroup = true, - FairDrawGender = true, + FairDrawGroup = false, + FairDrawGender = false, FairDrawTime = false, - MinWeight = 0, - MaxWeight = 10 + ColdStartEnabled = false, + Mode = FairDrawMode.RandomFirst }); using var host = BuildHost(config, new TestProfileService()); @@ -92,40 +92,43 @@ public void ShareDebtWeightsUsePersonalAndEnabledDimensionDebt() { [first] = new() { TotalCount = 0 }, [second] = new() { TotalCount = 0 }, - [third] = new() { TotalCount = 1 } + [third] = new() { TotalCount = 2 } }); - Assert.Equal(weights[0].Weight, weights[1].Weight); - Assert.True(weights[0].Weight > weights[2].Weight); - Assert.Equal(1.0, weights.Sum(item => item.Weight), precision: 10); + Assert.Equal(0.5, weights[0].Weight, precision: 10); + Assert.Equal(0.5, weights[1].Weight, precision: 10); + Assert.Equal(0.0, weights[2].Weight); } [Fact] - public void ShareDebtDimensionHorizonScalesWithBatchSize() + public void UniformFirstKeepsEveryCandidateInThePoolDrawable() { - var first = new Student { Name = "A", Group = "G1", Gender = "男" }; - var second = new Student { Name = "B", Group = "G2", Gender = "女" }; - var settings = FairDrawPolicySnapshot.FromConfig(new FairDrawSettingsConfig + var first = new Student { Name = "A" }; + var second = new Student { Name = "B" }; + var third = new Student { Name = "C" }; + var config = BuildConfig(new FairDrawSettingsConfig { FairDraw = true, - FairDrawGroup = true, + FairDrawGroup = false, FairDrawGender = false, - FairDrawTime = false + FairDrawTime = false, + ColdStartEnabled = false, + Mode = FairDrawMode.UniformFirst }); - var history = new Dictionary - { - [first] = new() { TotalCount = 2 }, - [second] = new() { TotalCount = 0 } - }; - using var host = BuildHost(BuildConfig(new FairDrawSettingsConfig()), new TestProfileService()); - var engine = CreateEngine(host); - var single = engine.CalculateStudentWeight([first, second], settings with { BatchSize = 1 }, history); - var batch = engine.CalculateStudentWeight([first, second], settings with { BatchSize = 3 }, history); + using var host = BuildHost(config, new TestProfileService()); + var weights = CreateEngine(host).CalculateStudentWeight( + [first, second, third], + new Dictionary + { + [first] = new() { TotalCount = 0 }, + [second] = new() { TotalCount = 0 }, + [third] = new() { TotalCount = 1 } + }); - Assert.True(batch[0].Weight > single[0].Weight); - Assert.True(batch[1].Weight < single[1].Weight); - Assert.Equal(1.0, batch.Sum(item => item.Weight), precision: 10); + Assert.All(weights, item => Assert.True(item.Weight > 0)); + Assert.Equal(1.0, weights.Sum(item => item.Weight), precision: 10); + Assert.True(weights[2].Weight < weights[0].Weight); } [Fact] diff --git a/SecRandom.Core.Tests/FloatingWindowDockHandleTests.cs b/SecRandom.Core.Tests/FloatingWindowDockHandleTests.cs new file mode 100644 index 000000000..047a71c0e --- /dev/null +++ b/SecRandom.Core.Tests/FloatingWindowDockHandleTests.cs @@ -0,0 +1,104 @@ +using System.Globalization; +using SecRandom.Core.Abstraction; +using SecRandom.Core.Models; +using SecRandom.Core.Services.FloatingWindow; + +namespace SecRandom.Core.Tests; + +public class FloatingWindowDockHandleTests +{ + [Fact] + public void ChineseUi_AllowsExactlyOneCharacter() + { + Assert.Equal(1, FloatingWindowDockHandle.GetMaxTextLength(CultureInfo.GetCultureInfo("zh-CN"))); + Assert.Equal(1, FloatingWindowDockHandle.GetMaxTextLength(CultureInfo.GetCultureInfo("zh-TW"))); + } + + [Fact] + public void OtherLanguages_DoNotUseTheSingleCharacterRule() + { + Assert.Equal(4, FloatingWindowDockHandle.GetMaxTextLength(CultureInfo.GetCultureInfo("en-US"))); + Assert.Equal(4, FloatingWindowDockHandle.GetMaxTextLength(CultureInfo.GetCultureInfo("ja-JP"))); + // 没有语言信息时按“非中文”处理,宽松优先,避免把内容悄悄截掉 + Assert.Equal(4, FloatingWindowDockHandle.GetMaxTextLength(null)); + } + + [Fact] + public void NormalizeText_KeepsOnlyAllowedCharactersUpToLimit() + { + Assert.Equal("抽", FloatingWindowDockHandle.NormalizeText("抽", 1)); + Assert.Equal("Go", FloatingWindowDockHandle.NormalizeText(" Go ", 4)); + Assert.Equal("G", FloatingWindowDockHandle.NormalizeText("Go", 1)); + Assert.Equal(string.Empty, FloatingWindowDockHandle.NormalizeText(" ", 1)); + } + + [Fact] + public void NormalizeText_RejectsEmojiButKeepsOrdinarySymbols() + { + Assert.Equal("抽", FloatingWindowDockHandle.NormalizeText("🎲抽", 1)); + Assert.Equal("抽", FloatingWindowDockHandle.NormalizeText("抽🎲", 1)); + Assert.Equal(string.Empty, FloatingWindowDockHandle.NormalizeText("😀", 4)); + // 组合型 emoji(变体选择符 / ZWJ)也不能漏进来 + Assert.Equal(string.Empty, FloatingWindowDockHandle.NormalizeText("❤️", 4)); + // 普通字母和标点不是 emoji,照常保留 + Assert.Equal("A", FloatingWindowDockHandle.NormalizeText("A", 4)); + Assert.Equal("#", FloatingWindowDockHandle.NormalizeText("#", 4)); + // 换行之类的控制字符直接丢弃 + Assert.Equal("抽", FloatingWindowDockHandle.NormalizeText("抽\n", 1)); + } + + [Fact] + public void ResolveText_FallsBackToLocalizedDefault() + { + Assert.Equal("抽", FloatingWindowDockHandle.ResolveText("", "抽")); + Assert.Equal("抽", FloatingWindowDockHandle.ResolveText(null, "抽")); + Assert.Equal("抽", FloatingWindowDockHandle.ResolveText(" ", "抽")); + Assert.Equal("Go", FloatingWindowDockHandle.ResolveText("Go", "抽")); + Assert.Equal("Go", FloatingWindowDockHandle.ResolveText("Go🎲", "抽")); + } + + [Fact] + public void ResolveText_KeepsFourCharactersEvenOnChineseUi() + { + // 存储里的“Go”不因当前是中文界面而被截成一个字,切语言不丢内容 + Assert.Equal("Go", FloatingWindowDockHandle.ResolveText("Go", "抽")); + } + + [Fact] + public void TextFontScale_ShrinksAsTextGrows() + { + Assert.True(FloatingWindowDockHandle.GetTextFontScale(1) > + FloatingWindowDockHandle.GetTextFontScale(2)); + Assert.True(FloatingWindowDockHandle.GetTextFontScale(2) > + FloatingWindowDockHandle.GetTextFontScale(4)); + } + + [Fact] + public void StyleConstants_AreStable() + { + Assert.True(FloatingWindowDockHandle.IsIconStyle(FloatingWindowDockHandle.IconStyle)); + Assert.True(FloatingWindowDockHandle.IsTextStyle(FloatingWindowDockHandle.TextStyle)); + Assert.False(FloatingWindowDockHandle.IsTextStyle(FloatingWindowDockHandle.ArrowStyle)); + Assert.NotEqual(FloatingWindowDockHandle.LeftArrowGlyph, FloatingWindowDockHandle.RightArrowGlyph); + } + + [Fact] + public void Config_DockHandleFieldsRoundTripThroughJson() + { + MainConfigModel config = new(); + config.FloatingWindowSettings.StickToEdgeDisplayStyle = FloatingWindowDockHandle.ArrowStyle; + config.FloatingWindowSettings.StickToEdgeDisplayText = "抽"; + config.FloatingWindowSettings.StickToEdgeDisplayIconGlyph = "PeopleFilled"; + config.FloatingWindowSettings.StickToEdgeDisplayIconImage = "abc.png"; + + string json = System.Text.Json.JsonSerializer.Serialize(config, ConfigServiceBase.JsonOptions); + MainConfigModel? restored = + System.Text.Json.JsonSerializer.Deserialize(json, ConfigServiceBase.JsonOptions); + + Assert.NotNull(restored); + Assert.Equal(FloatingWindowDockHandle.ArrowStyle, restored.FloatingWindowSettings.StickToEdgeDisplayStyle); + Assert.Equal("抽", restored.FloatingWindowSettings.StickToEdgeDisplayText); + Assert.Equal("PeopleFilled", restored.FloatingWindowSettings.StickToEdgeDisplayIconGlyph); + Assert.Equal("abc.png", restored.FloatingWindowSettings.StickToEdgeDisplayIconImage); + } +} \ No newline at end of file diff --git a/SecRandom.Core.Tests/FloatingWindowSettingsConfigTests.cs b/SecRandom.Core.Tests/FloatingWindowSettingsConfigTests.cs index 239f782ed..09ebbc965 100644 --- a/SecRandom.Core.Tests/FloatingWindowSettingsConfigTests.cs +++ b/SecRandom.Core.Tests/FloatingWindowSettingsConfigTests.cs @@ -86,4 +86,22 @@ public void MainConfig_SyncBothSidesAnchorDefaultsOnAndRoundTrips() Assert.NotNull(restored); Assert.False(restored.FloatingWindowSettings.SyncBothSidesAnchor); } + + [Fact] + public void MainConfig_QuickDrawLongPressDefaultsOnAndRoundTrips() + { + MainConfigModel config = new(); + Assert.True(config.FloatingWindowSettings.EnableQuickDrawLongPress); + Assert.Equal(500, config.FloatingWindowSettings.LongPressDuration); + + config.FloatingWindowSettings.EnableQuickDrawLongPress = false; + config.FloatingWindowSettings.LongPressDuration = 800; + + string json = JsonSerializer.Serialize(config, ConfigServiceBase.JsonOptions); + MainConfigModel? restored = JsonSerializer.Deserialize(json, ConfigServiceBase.JsonOptions); + + Assert.NotNull(restored); + Assert.False(restored.FloatingWindowSettings.EnableQuickDrawLongPress); + Assert.Equal(800, restored.FloatingWindowSettings.LongPressDuration); + } } diff --git a/SecRandom.Core.Tests/HistoryGroupCommitTests.cs b/SecRandom.Core.Tests/HistoryGroupCommitTests.cs index 03a0f5d92..8f551da83 100644 --- a/SecRandom.Core.Tests/HistoryGroupCommitTests.cs +++ b/SecRandom.Core.Tests/HistoryGroupCommitTests.cs @@ -96,6 +96,81 @@ public void StudentCommit_WithCourseAndGroup_StampsBothAxes() Assert.Equal("课堂", item.HistoryGroup); } + [Fact] + public void StudentCommit_RecordGroupOverridesTheReadScope() + { + // 读取范围可以是「不按组筛」,写入归属必须另算:两者混用会让一次按组读取的抽取把记录塞进 + // 用户已经切走的那个组里。 + using var provider = CreateProvider(); + var profile = provider.GetRequiredService(); + var student = new Student { Name = "Ada", RecordId = Guid.NewGuid() }; + profile.CurrentStudentList!.Students.Add(student); + profile.SaveProfile(); + + provider.GetRequiredService().CommitStudentDraw(new StudentDrawCommit( + [student], + DateTime.Now, + 1, + profile.StudentListConfig!.Name, + HistoryGroup: "课堂", + RecordGroup: "点名默认组")); + + var item = profile.CurrentStudentHistory!.Students.Values.SelectMany(history => history.Histories).Single(); + Assert.Equal("点名默认组", item.HistoryGroup); + } + + [Fact] + public void StudentCommit_UnscopedReadStillStampsTheChannelsDefaultGroup() + { + // 功能关闭、选择器不可见时读取范围是 null(全部历史),但记录仍落在顶点名自己配置的默认组上: + // 否则点名、闪抽、抽奖会一起挤进默认组,重新打开功能就拆不回来。 + using var provider = CreateProvider(); + var profile = provider.GetRequiredService(); + var student = new Student { Name = "Bo", RecordId = Guid.NewGuid() }; + profile.CurrentStudentList!.Students.Add(student); + profile.SaveProfile(); + + provider.GetRequiredService().CommitStudentDraw(new StudentDrawCommit( + [student], + DateTime.Now, + 1, + profile.StudentListConfig!.Name, + RecordGroup: "点名默认组")); + + var item = profile.CurrentStudentHistory!.Students.Values.SelectMany(history => history.Histories).Single(); + Assert.Equal("点名默认组", item.HistoryGroup); + } + + [Fact] + public void LotteryCommit_StampsPrizeAndAssignedStudentGroupsSeparately() + { + // 抽奖连带抽中的学生在学生历史里是另一条通道:奖品那组的名字对学生历史不可见, + // 所以两边各用自己的写入归属,而不是共用 commit.HistoryGroup。 + using var provider = CreateProvider(); + var profile = provider.GetRequiredService(); + var prize = new Prize { Name = "铅笔", RecordId = Guid.NewGuid(), Count = 1 }; + var student = new Student { Name = "Cy", RecordId = Guid.NewGuid() }; + profile.CurrentPrizeList!.Prizes.Add(prize); + profile.CurrentStudentList!.Students.Add(student); + profile.SaveProfile(); + + provider.GetRequiredService().CommitLotteryDraw(new LotteryDrawCommit( + [prize], + DateTime.Now, + 1, + profile.PrizeListConfig!.Name, + AssignedStudents: [student], + StudentListName: profile.StudentListConfig!.Name, + RecordGroup: "奖品默认组", + StudentRecordGroup: "点名默认组")); + + var prizeItem = profile.CurrentPrizeHistory!.Prizes.Values.SelectMany(history => history.Histories).Single(); + var studentItem = profile.CurrentStudentHistory!.Students.Values.SelectMany(history => history.Histories).Single(); + + Assert.Equal("奖品默认组", prizeItem.HistoryGroup); + Assert.Equal("点名默认组", studentItem.HistoryGroup); + } + [Fact] public void StudentCommit_RollsBackHistoryGroupMarkersWhenHistorySaveFails() { diff --git a/SecRandom.Core.Tests/HistoryGroupDefaultScopeTests.cs b/SecRandom.Core.Tests/HistoryGroupDefaultScopeTests.cs index ff9fe3a5a..93943daf1 100644 --- a/SecRandom.Core.Tests/HistoryGroupDefaultScopeTests.cs +++ b/SecRandom.Core.Tests/HistoryGroupDefaultScopeTests.cs @@ -81,3 +81,59 @@ public void UnreadableCatalogue_DoesNotNarrowTheWeightPool() Assert.False(scope.ConfiguredGroupMissing); } } + +/// +/// Write-side counterpart of the same decision: which group marker a new record carries. It is deliberately a +/// separate entry point, because the feature master switch only governs whether the selector may be shown — a +/// channel whose history is not group-scoped still writes its own configured default group. Collapsing the two +/// would let every mode pile into the default group as soon as the feature is turned off, which cannot be undone +/// by turning it back on. +/// +public sealed class HistoryRecordGroupWriteScopeTests +{ + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" ")] + public void BlankConfiguration_WritesTheDefaultGroup(string? configured) + { + Assert.Equal(string.Empty, HistoryGroupScope.ResolveRecordGroup(configured, ["Class A"])); + } + + [Fact] + public void ExistingGroup_IsWrittenAndTrimmed() + { + Assert.Equal("Class A", HistoryGroupScope.ResolveRecordGroup(" Class A ", ["Class A", "Class B"])); + } + + [Fact] + public void UnreadableCatalogue_KeepsTheConfiguredName() + { + // The opposite of the read side, on purpose: a name is only a marker, so keeping what the user configured is + // the recoverable choice, while silently folding the records into the default group is irreversible. + Assert.Equal("Class A", HistoryGroupScope.ResolveRecordGroup("Class A", null)); + } + + [Fact] + public void DeletedGroup_WritesTheDefaultGroupInsteadOfAGhostName() + { + Assert.Equal(string.Empty, HistoryGroupScope.ResolveRecordGroup("Deleted", ["Class A"])); + } + + [Fact] + public void MatchingIsOrdinal() + { + Assert.Equal(string.Empty, HistoryGroupScope.ResolveRecordGroup("class a", ["Class A"])); + } + + [Fact] + public void TheFeatureSwitch_IsNotPartOfTheWriteDecision() + { + // Pinned by signature: adding an `enabled` parameter here would re-introduce exactly the collapse this type + // exists to prevent (feature off ⇒ every mode writes the default group). + var method = typeof(HistoryGroupScope).GetMethod(nameof(HistoryGroupScope.ResolveRecordGroup)); + + Assert.NotNull(method); + Assert.Equal(2, method!.GetParameters().Length); + } +} diff --git a/SecRandom.Core.Tests/HistoryGroupLocalizationTests.cs b/SecRandom.Core.Tests/HistoryGroupLocalizationTests.cs index 143721ee0..d953c2de6 100644 --- a/SecRandom.Core.Tests/HistoryGroupLocalizationTests.cs +++ b/SecRandom.Core.Tests/HistoryGroupLocalizationTests.cs @@ -68,8 +68,7 @@ private static readonly (string[] Folder, string[] Keys)[] CoveredFolders = "S_LotteryHistoryGroup_D", "S_QuickDrawHistoryGroup", "S_QuickDrawHistoryGroup_D", - "O_HistoryGroupDefault", - "S_HistoryGroup_Disabled" + "O_HistoryGroupDefault" ]), (["SettingsPages", "More"], [ @@ -106,7 +105,7 @@ private static readonly (string[] Folder, string[] Keys)[] CoveredFolders = "S_HistoryGroup_Move", "S_HistoryGroup_MoveHint", "S_HistoryGroup_MoveDone", - "S_HistoryGroup_New", + "S_HistoryGroup_MoveNothing", "S_Filter_HistoryGroup" ]; diff --git a/SecRandom.Core.Tests/HistoryGroupMoveTests.cs b/SecRandom.Core.Tests/HistoryGroupMoveTests.cs index 64d2e0047..d547f0e4a 100644 --- a/SecRandom.Core.Tests/HistoryGroupMoveTests.cs +++ b/SecRandom.Core.Tests/HistoryGroupMoveTests.cs @@ -236,6 +236,61 @@ public void MovePrizeHistoryGroup_ChangesOnlyTheMarker() Assert.Equal("抽奖组", reloaded!.Prizes[key].Histories.Single().HistoryGroup); } + [Fact] + public void MoveStudentHistoryGroup_ScopedBySourceGroupLeavesOtherGroupsAlone() + { + using var provider = CreateProvider(); + var manager = provider.GetRequiredService(); + var profile = provider.GetRequiredService(); + var (alice, _) = SeedRollCallProfile(provider, manager, profile); + + var history = profile.CurrentStudentHistory!; + var profileName = profile.StudentHistoryConfig!.Name; + var key = ProfileRecordIdentity.EnsureRecordId(alice); + profile.RecordStudentHistory([alice], new DateTime(2026, 8, 31, 9, 0, 0), 1, historyGroup: "课堂"); + + // 记录组筛选停在「默认记录组」时移动:只改默认组那一条,另一条「课堂」记录原地不动。 + Assert.Equal(1, manager.MoveStudentHistoryGroup(profileName, [key], "抽奖", sourceGroup: string.Empty)); + Assert.Equal(["抽奖", "课堂"], history.Students[key].Histories.Select(item => item.HistoryGroup)); + Assert.Equal(2, history.Students[key].Histories.Count); + Assert.Equal(2, history.Students[key].TotalCount); + + // 筛选值就是目标组:该组记录已经在目标组,没有可改的标记,因此返回 0 且不写盘。 + var path = Utils.GetFilePath("history", "roll_call_history", $"{profileName}{Utils.HistoryDatabaseExtension}"); + var bytesBefore = File.ReadAllBytes(path); + Assert.Equal(0, manager.MoveStudentHistoryGroup(profileName, [key], "抽奖", sourceGroup: "抽奖")); + Assert.Equal(bytesBefore, File.ReadAllBytes(path)); + + // 不带 sourceGroup 仍是「整个成员」的旧行为:两条记录一起改。 + Assert.Equal(1, manager.MoveStudentHistoryGroup(profileName, [key], "课堂")); + Assert.Equal(["课堂", "课堂"], history.Students[key].Histories.Select(item => item.HistoryGroup)); + } + + [Fact] + public void MovePrizeHistoryGroup_ScopedBySourceGroupLeavesOtherGroupsAlone() + { + using var provider = CreateProvider(); + var manager = provider.GetRequiredService(); + var profile = provider.GetRequiredService(); + Assert.True(manager.CreatePrizeList("pool-scope")); + profile.LoadPrizeProfile("pool-scope"); + + var book = new Prize { Name = "Book", Id = "A1", Count = 2, RecordId = Guid.NewGuid() }; + profile.CurrentPrizeList!.Prizes.Add(book); + profile.SaveProfile(); + profile.RecordPrizeHistory([book], new DateTime(2026, 8, 30, 8, 0, 0), 1); + profile.RecordPrizeHistory([book], new DateTime(2026, 8, 30, 9, 0, 0), 1, historyGroup: "抽奖组"); + + var history = profile.CurrentPrizeHistory!; + var key = ProfileRecordIdentity.EnsureRecordId(book); + + Assert.Equal(1, manager.MovePrizeHistoryGroup("pool-scope", [key], "课堂", sourceGroup: string.Empty)); + Assert.Equal(["课堂", "抽奖组"], history.Prizes[key].Histories.Select(item => item.HistoryGroup)); + + var reloaded = provider.GetRequiredService().LoadPrizeHistory("pool-scope"); + Assert.Equal(["课堂", "抽奖组"], reloaded!.Prizes[key].Histories.Select(item => item.HistoryGroup)); + } + public void Dispose() { ResetDataRootForTests(); diff --git a/SecRandom.Core.Tests/LinkageDrawCoordinatorTests.cs b/SecRandom.Core.Tests/LinkageDrawCoordinatorTests.cs new file mode 100644 index 000000000..fe8a165e5 --- /dev/null +++ b/SecRandom.Core.Tests/LinkageDrawCoordinatorTests.cs @@ -0,0 +1,255 @@ +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging.Abstractions; +using SecRandom.Core.Abstraction; +using SecRandom.Core.Enums.Configs; +using SecRandom.Core.Models; +using SecRandom.Core.Services.Config; +using SecRandom.Core.Services.ControlNode; +using SecRandom.Services.Linkage; +using SecRandom.Services.Security; + +namespace SecRandom.Core.Tests; + +/// +/// 联动闸门在「允许验证后继续」下的拒绝语义。 +/// +/// 该开关只承诺"验证之后可以继续"。当宿主没有可用的验证手段(安全保护未启用、 +/// 没有任何已配置的验证方式)时,SecurityService 对 BypassClassTimeRestriction 也返回 +/// "无需验证"并直接执行动作;闸门若原样转交,课间禁令与"数据源不可用时维持限制" +/// 就会整体 fail-open —— 开关看着是开的,抽取却照常发生。 +/// +/// +public sealed class LinkageDrawCoordinatorTests +{ + [Fact] + public async Task StrictRestriction_WithoutConfiguredVerification_BlocksDraw() + { + var harness = new Harness(restrictWhenUnavailable: true, verificationAvailable: false); + + var executed = false; + var authorized = await harness.Coordinator.AuthorizeAsync( + SecurityOperation.RollCallStart, () => { executed = true; return Task.CompletedTask; }); + + Assert.False(authorized); + Assert.False(executed); + Assert.Equal(LinkageDrawGate.BlockedByClassTime, harness.Coordinator.EvaluateGate(SecurityOperation.RollCallStart)); + } + + [Fact] + public async Task StrictRestriction_WithConfiguredVerification_RunsTheAction() + { + var harness = new Harness(restrictWhenUnavailable: true, verificationAvailable: true); + + var executed = false; + var authorized = await harness.Coordinator.AuthorizeAsync( + SecurityOperation.RollCallStart, () => { executed = true; return Task.CompletedTask; }); + + Assert.True(authorized); + Assert.True(executed); + Assert.Equal(LinkageDrawGate.RequiresLocalVerification, harness.Coordinator.EvaluateGate(SecurityOperation.RollCallStart)); + } + + [Fact] + public async Task UnavailableSource_WithoutStrictRestriction_StaysAllowed() + { + var harness = new Harness(restrictWhenUnavailable: false, verificationAvailable: false); + + var executed = false; + var authorized = await harness.Coordinator.AuthorizeAsync( + SecurityOperation.RollCallStart, () => { executed = true; return Task.CompletedTask; }); + + Assert.True(authorized); + Assert.True(executed); + Assert.False(harness.Linkage.IsClassTimeRestrictionActive); + Assert.Equal(LinkageDrawGate.Allowed, harness.Coordinator.EvaluateGate(SecurityOperation.RollCallStart)); + } + + [Fact] + public async Task VerificationDisabled_BlocksEvenWhenVerificationIsConfigured() + { + var harness = new Harness( + restrictWhenUnavailable: true, + verificationAvailable: true, + verificationRequired: false); + + var executed = false; + var authorized = await harness.Coordinator.AuthorizeAsync( + SecurityOperation.RollCallStart, () => { executed = true; return Task.CompletedTask; }); + + Assert.False(authorized); + Assert.False(executed); + Assert.Equal(LinkageDrawGate.BlockedByClassTime, harness.Coordinator.EvaluateGate(SecurityOperation.RollCallStart)); + } + + private sealed class Harness + { + public Harness( + bool restrictWhenUnavailable, + bool verificationAvailable, + bool verificationRequired = true) + { + var config = new MainConfigModel(); + config.LinkageSettings.DataSource = LinkageDataSource.Cses; + config.LinkageSettings.InstantDrawDisable = true; + config.LinkageSettings.RestrictWhenUnavailable = restrictWhenUnavailable; + config.LinkageSettings.VerificationRequired = verificationRequired; + + var handler = new MainConfigHandler( + NullLogger.Instance, + new TestConfigService(config)); + var store = new MissingCsesScheduleStore(); + var connection = new ClassIslandIpcConnection(NullLogger.Instance); + var source = new ClassIslandScheduleSource(connection, NullLogger.Instance); + Linkage = new CourseLinkageService( + handler, + store, + new CsesScheduleSource(store), + source, + NullLogger.Instance); + Coordinator = new LinkageDrawCoordinator( + Linkage, + new StubSecurityService(verificationAvailable), + new UnlockedControlDrawGate()); + // CSES 数据源已选择但课表缺失 —— 正是"数据源不可用"的场景。 + Linkage.RefreshAsync().GetAwaiter().GetResult(); + } + + public CourseLinkageService Linkage { get; } + public LinkageDrawCoordinator Coordinator { get; } + } + + private sealed class StubSecurityService(bool verificationAvailable) : ISecurityService + { + public SecuritySettingsUiState GetUiState() => new(false, false, false, false, false, false, false, null); + + public bool RequiresVerification(SecurityOperation operation) => verificationAvailable; + + public Task VerifyAsync( + SecurityVerificationResponse response, + CancellationToken cancellationToken = default) + => Task.FromResult(SecurityVerificationResult.Allowed); + + public Task AuthorizeAsync( + SecurityOperation operation, + Func action, + CancellationToken cancellationToken = default) + => AuthorizeAsync([operation], action, cancellationToken); + + public async Task AuthorizeAsync( + IReadOnlyCollection operations, + Func action, + CancellationToken cancellationToken = default) + { + await action(); + return true; + } + + public Task AuthorizePasswordAsync( + Avalonia.Controls.TopLevel xamlRoot, + Func action, + CancellationToken cancellationToken = default) + => AuthorizeAsync(SecurityOperation.OpenSettings, action, cancellationToken); + + public Task AuthorizeSettingsAsync( + Func action, + Func previewAction, + CancellationToken cancellationToken = default) + => Task.FromResult(new SecurityAuthorizationResult(true)); + + public Task UpdateSecuritySettingsAsync( + Avalonia.Controls.TopLevel xamlRoot, + Action update, + CancellationToken cancellationToken = default) + { + update(); + return Task.FromResult(true); + } + + public Task SetPasswordAsync(string password, string? currentPassword = null, + CancellationToken cancellationToken = default) => Task.FromResult(true); + + public Task RemovePasswordAsync(string currentPassword, CancellationToken cancellationToken = default) + => Task.FromResult(true); + + public Task BeginTotpSetupAsync(CancellationToken cancellationToken = default) + => Task.FromResult(null); + + public Task BeginTotpSetupAsync(Avalonia.Controls.TopLevel xamlRoot, + CancellationToken cancellationToken = default) => Task.FromResult(null); + + public Task CancelTotpSetupAsync(string secret, CancellationToken cancellationToken = default) + => Task.CompletedTask; + + public Task ConfirmTotpAsync(string secret, string code, CancellationToken cancellationToken = default) + => Task.FromResult(true); + + public Task RemoveTotpAsync(Avalonia.Controls.TopLevel xamlRoot, + CancellationToken cancellationToken = default) => Task.FromResult(true); + + public Task> GetUsbBindingsAsync(CancellationToken cancellationToken = default) + => Task.FromResult>([]); + + public Task> GetUsbDevicesAsync(CancellationToken cancellationToken = default) + => Task.FromResult>([]); + + public Task BindUsbAsync(string deviceId, CancellationToken cancellationToken = default) + => Task.FromResult(true); + + public Task BindUsbAsync(Avalonia.Controls.TopLevel xamlRoot, string deviceId, + CancellationToken cancellationToken = default) => Task.FromResult(true); + + public Task UnbindUsbAsync(string bindingId, CancellationToken cancellationToken = default) + => Task.FromResult(true); + + public Task UnbindUsbAsync(Avalonia.Controls.TopLevel xamlRoot, string bindingId, + CancellationToken cancellationToken = default) => Task.FromResult(true); + + public bool TryUpdateSettings(Action update) + { + update(); + return true; + } + + public Task AuthorizeArchiveImportAsync(CancellationToken cancellationToken = default) + => Task.FromResult(true); + + public bool IsSudoModeActive() => false; + + public bool IsGlobalSudoModeActive() => false; + + public void DeactivateGlobalSudoMode() { } + + public void DeactivateSudoMode() { } + + public void DeactivateSettingsSudoMode() { } + + public event Action? SudoModeChanged + { + add { } + remove { } + } + } + + private sealed class MissingCsesScheduleStore : ICsesScheduleStore + { + public string SchedulePath => "unused"; + public event EventHandler? ScheduleChanged { add { } remove { } } + public CsesSchedule? Load() => null; + + public Task ImportAsync(string sourcePath, CancellationToken cancellationToken = default) + => throw new NotSupportedException(); + + public void Clear() { } + } + + 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) { } + } +} \ No newline at end of file diff --git a/SecRandom.Core.Tests/LocalizationHygieneTests.cs b/SecRandom.Core.Tests/LocalizationHygieneTests.cs index 8275bea79..f90ae5805 100644 --- a/SecRandom.Core.Tests/LocalizationHygieneTests.cs +++ b/SecRandom.Core.Tests/LocalizationHygieneTests.cs @@ -125,6 +125,33 @@ public sealed class LocalizationHygieneTests + string.Join(Environment.NewLine, failures)); } + [Fact] + public void 文案库AI区块四键三语齐全并有生成器属性() + { + string directory = Path.Combine(LangsRoot, "SettingsPages", "Notification", "Texts"); + var zh = Entries(Path.Combine(directory, "Resources.resx")).ToDictionary(); + var en = Entries(Path.Combine(directory, "Resources.en-US.resx")).ToDictionary(); + var ja = Entries(Path.Combine(directory, "Resources.ja-JP.resx")).ToDictionary(); + var designer = File.ReadAllText(Path.Combine(directory, "Resources.Designer.cs")); + string[] keys = ["M_JsonAiTitle", "M_JsonAiHint", "C_JsonAiCopy", "M_JsonAiCopied"]; + + foreach (var key in keys) + { + Assert.True(zh.ContainsKey(key), $"Resources.resx 缺少 {key}"); + Assert.True(en.ContainsKey(key), $"Resources.en-US.resx 缺少 {key}"); + Assert.True(ja.ContainsKey(key), $"Resources.ja-JP.resx 缺少 {key}"); + Assert.Contains($"public static string {key} ", designer, StringComparison.Ordinal); + Assert.False(string.IsNullOrWhiteSpace(zh[key]), $"{key} 的中文值为空"); + Assert.False(string.IsNullOrWhiteSpace(en[key]), $"{key} 的英文值为空"); + Assert.False(string.IsNullOrWhiteSpace(ja[key]), $"{key} 的日文值为空"); + } + + // 提示词正文是代码里的英文常量,不再占用 resx;这里只守住界面上的四个键。 + Assert.False(zh.ContainsKey("M_JsonAiPrompt"), "M_JsonAiPrompt 已移入代码,resx 不应再保留"); + Assert.False(en.ContainsKey("M_JsonAiPrompt"), "M_JsonAiPrompt 已移入代码,resx 不应再保留"); + Assert.False(ja.ContainsKey("M_JsonAiPrompt"), "M_JsonAiPrompt 已移入代码,resx 不应再保留"); + } + private static bool IsDescriptionKey(string key) => key.EndsWith("_D", StringComparison.Ordinal); /// diff --git a/SecRandom.Core.Tests/MobileRemoteDrawTests.cs b/SecRandom.Core.Tests/MobileRemoteDrawTests.cs deleted file mode 100644 index 90548799e..000000000 --- a/SecRandom.Core.Tests/MobileRemoteDrawTests.cs +++ /dev/null @@ -1,1859 +0,0 @@ -using System.Globalization; -using System.Net; -using System.Text; -using System.Text.Json; -using System.Text.RegularExpressions; -using Microsoft.Extensions.Logging.Abstractions; -using SecRandom.Core; -using SecRandom.Core.Abstraction; -using SecRandom.Core.Models; -using SecRandom.Core.Services.Config; -using SecRandom.Core.Services.ControlNode; -using SecRandom.Services.Auth; -using SecRandom.Services.Config; -using SecRandom.Services.ControlNode; -using SecRandom.Services.ControlPlane; -using SecRandom.Shared.Models.ControlNode; -using SecRandom.Shared.Models.ControlPlane; -using SecRandom.ViewModels.Mobile; -using LR = SecRandom.Langs.Mobile.Resources; - -namespace SecRandom.Core.Tests; - -/// -/// 手机端远程抽取页:设备行的可用性判定、上次选中设备的记忆、失败文案与三语覆盖。 -/// -/// -/// 页面本身要在真机/模拟器上跑,但"哪台设备能用""失败时说什么""三语有没有漏" -/// 都是纯逻辑,放在这里逐条钉住——这几件事错了只会被用户看到(按钮点不动、文案空白)。 -/// -public sealed class MobileRemoteDrawTests : IDisposable -{ - private readonly string _preferencePath = Path.Combine( - Path.GetTempPath(), "SecRandom", "control-plane-preference-tests", Guid.NewGuid().ToString("N"), "last-device.json"); - - public void Dispose() - { - var directory = Path.GetDirectoryName(_preferencePath); - if (directory is not null && Directory.Exists(directory)) - Directory.Delete(directory, recursive: true); - } - - // ---------------------------------------------------------------- 设备行 - - [Fact] - public void 设备行_名字缺失时回落节点id且状态可读() - { - var row = Row( - new GroupDto { GroupId = "g1", Name = "高一(1)班", Role = "admin" }, - new NodeDto - { - NodeId = "node-7", - DisplayName = " ", - Online = true, - LocalRemoteAllowed = true, - Capabilities = [ControlCapabilities.DrawTrigger, ControlCapabilities.RosterRead] - }); - - Assert.Equal("node-7", row.DeviceLabel); - Assert.Equal("高一(1)班", row.GroupLabel); - Assert.Equal(LR.RD_Online, row.StatusText); - Assert.True(row.IsUsable); - Assert.Null(row.UnavailableReason); - Assert.Contains("node-7", row.Summary, StringComparison.Ordinal); - } - - [Fact] - public void 设备行_本机关闭远控的设备不可用且写明原因() - { - var row = Row( - new GroupDto { GroupId = "g1", Name = "高一(1)班", Role = "operator" }, - new NodeDto - { - NodeId = "n1", - DisplayName = "讲台机", - Online = true, - LocalRemoteAllowed = false, - Capabilities = [ControlCapabilities.DrawTrigger, ControlCapabilities.RosterRead] - }); - - Assert.False(row.IsUsable); - Assert.True(row.IsRemoteDisabled); - Assert.Equal(LR.RD_RemoteDisabled, row.StatusText); - Assert.Equal(LR.RD_RemoteDisabled, row.UnavailableReason); - } - - [Theory] - // 没有名单读取 → 选不了名单;没有抽取 → 点不了抽取。两种原因必须能区分。 - [InlineData(new[] { "draw.trigger" }, "RD_MissingRosterCapability")] - [InlineData(new[] { "roster.read" }, "RD_MissingDrawCapability")] - [InlineData(new string[0], "RD_MissingRosterCapability")] - public void 设备行_能力缺失时置灰并写出缺的是哪一项(string[] capabilities, string expectedKey) - { - var row = Row( - new GroupDto { GroupId = "g1", Name = "组", Role = "admin" }, - new NodeDto - { - NodeId = "n1", - Online = true, - LocalRemoteAllowed = true, - Capabilities = capabilities - }); - - Assert.False(row.IsUsable); - Assert.NotNull(row.UnavailableReason); - Assert.Equal(Expected(expectedKey), row.UnavailableReason); - } - - [Fact] - public void 设备行_离线仍然可选但要写明上线后执行() - { - var row = Row( - new GroupDto { GroupId = "g1", Name = "组", Role = "admin" }, - new NodeDto - { - NodeId = "n1", - Online = false, - LocalRemoteAllowed = true, - Capabilities = [ControlCapabilities.DrawTrigger, ControlCapabilities.RosterRead] - }); - - // 离线不是硬拒绝:命令会在它上线后补投,因此仍然可选、只是标注清楚。 - Assert.True(row.IsUsable); - Assert.Equal(LR.RD_OfflineQueued, row.StatusText); - Assert.Null(row.UnavailableReason); - } - - [Fact] - public void 设备行_按组与节点共同定位() - { - var row = Row( - new GroupDto { GroupId = "g1", Name = "组一" }, - new NodeDto { NodeId = "n1", DisplayName = "同一台机器" }); - - Assert.True(row.Matches("g1", "n1")); - // 同一台机器挂在另一个组下是另一行:匹配必须同时看组。 - Assert.False(row.Matches("g2", "n1")); - Assert.False(row.Matches("g1", "n2")); - Assert.False(row.Matches(null, "n1")); - } - - // ---------------------------------------------------------------- 上次选中的设备 - - [Fact] - public void 记住设备_写入后能读回并且覆盖写不叠加() - { - var store = new FileControlPlaneDevicePreferenceStore(_preferencePath); - - Assert.Null(store.Load()); - - store.Save(new ControlPlaneDevicePreference("g1", "n1")); - var first = store.Load(); - Assert.NotNull(first); - Assert.Equal("g1", first!.GroupId); - Assert.Equal("n1", first.NodeId); - - store.Save(new ControlPlaneDevicePreference("g2", "n2")); - var second = store.Load(); - Assert.Equal("g2", second!.GroupId); - Assert.Equal("n2", second.NodeId); - - // 原子替换:临时文件不该留在那里。 - Assert.False(File.Exists(_preferencePath + ".tmp")); - } - - [Theory] - [InlineData("{ not json")] - [InlineData("""{ "group_id": "", "node_id": "n1" }""")] - [InlineData("""{ "group_id": "g1" }""")] - [InlineData("null")] - public void 记住设备_坏文件一律回落而不是抛异常(string content) - { - Directory.CreateDirectory(Path.GetDirectoryName(_preferencePath)!); - File.WriteAllText(_preferencePath, content); - - // 一个记不住上次选择的手机不该打不开抽取页。 - Assert.Null(new FileControlPlaneDevicePreferenceStore(_preferencePath).Load()); - } - - // ---------------------------------------------------------------- 失败文案 - - [Theory] - [InlineData(ControlPlaneErrorKind.Unauthorized)] - [InlineData(ControlPlaneErrorKind.Forbidden)] - [InlineData(ControlPlaneErrorKind.NotFound)] - [InlineData(ControlPlaneErrorKind.Timeout)] - [InlineData(ControlPlaneErrorKind.Network)] - [InlineData(ControlPlaneErrorKind.RateLimited)] - public void 失败文案_请求类失败都是人话且非空(ControlPlaneErrorKind kind) - { - var message = ControlPlaneMessages.Describe(new ControlPlaneException("code", kind)); - - Assert.False(string.IsNullOrWhiteSpace(message)); - Assert.DoesNotContain("code", message, StringComparison.Ordinal); - } - - [Fact] - public void 失败文案_请求类失败保留未知错误码() - { - // 藏成"未知错误"的话,运维拿着截图没法去日志里搜。 - var message = ControlPlaneMessages.Describe( - new ControlPlaneException("teapot_mode", ControlPlaneErrorKind.Unknown)); - - Assert.Contains("teapot_mode", message, StringComparison.Ordinal); - } - - [Theory] - [InlineData("local_remote_disabled")] - [InlineData("draw_locked")] - [InlineData("busy")] - [InlineData("capability_unsupported")] - [InlineData("expired")] - public void 失败文案_设备侧原因码逐条有对应说法(string code) - { - var message = ControlPlaneMessages.DescribeCommand(FailedCommand(code)); - - Assert.False(string.IsNullOrWhiteSpace(message)); - // 人话 + **原始错误码**:排查时只知道"设备拒绝了"是没法定位的。 - Assert.Contains(code, message, StringComparison.Ordinal); - } - - [Fact] - public void 失败文案_抽取被拒时区分上课时间与需要本机验证() - { - var classTime = ControlPlaneMessages.DescribeCommand( - FailedCommand("draw_denied", new { reason = "blocked_by_class_time" })); - var verification = ControlPlaneMessages.DescribeCommand( - FailedCommand("draw_denied", new { reason = "local_verification_required" })); - - Assert.StartsWith(LR.RD_ClassTime, classTime, StringComparison.Ordinal); - Assert.StartsWith(LR.RD_Denied, verification, StringComparison.Ordinal); - Assert.NotEqual(classTime, verification); - } - - [Theory] - // 设备侧形状:整条原因码就是 invalid_value:<字段>:<为什么> - [InlineData("invalid_value:list_name:not_found", null, null, "RD_ListNotFound", null)] - [InlineData("invalid_value:gender:not_in_list", null, null, "RD_NotInList", null)] - [InlineData("invalid_value:count:out_of_range", null, null, "RD_OutOfRange", null)] - // 名单整体没有可抽的人 ≠ 条件筛完没有人:两句文案必须不同。 - [InlineData("invalid_value:list_name:no_candidate", null, null, "RD_NoRosterCandidate", null)] - [InlineData("invalid_value:gender:no_matching_member", null, null, "RD_NoCandidate", null)] - // 服务端形状:码与字段分开给 - [InlineData("invalid_value", "count", "type_mismatch", "RD_InvalidValueField", "count")] - [InlineData("invalid_value", "gender", "not_in_list", "RD_NotInList", null)] - public void 失败文案_非法取值按字段与细因给出可行动的话( - string code, - string? field, - string? why, - string expectedKey, - string? formatField) - { - var message = ControlPlaneMessages.DescribeCommand(FailedCommand(code, field, why)); - var expected = formatField is null ? Expected(expectedKey) : string.Format(Expected(expectedKey), formatField); - - Assert.StartsWith(expected, message, StringComparison.Ordinal); - // 原始错误码一并显示。 - Assert.Contains(code, message, StringComparison.Ordinal); - } - - [Fact] - public void 失败文案_没有原因的失败说抽取失败而不是空白() - { - Assert.Equal(LR.RD_Failed, ControlPlaneMessages.DescribeCommand(FailedCommand(null))); - Assert.Equal( - LR.RD_CommandTimeout, - ControlPlaneMessages.DescribeCommand(new NodeCommandDto { CommandId = "c", Status = "pending" })); - } - - // ---------------------------------------------------------------- 接线 - - [Fact] - public void 接线_底部导航有第五个入口且页面与视图模型都注册了() - { - var rootView = File.ReadAllText(GetRepositoryPath("SecRandom/Views/Mobile/MobileRootView.axaml")); - Assert.Contains("langs:Resources.N_RemoteDraw", rootView, StringComparison.Ordinal); - // 五档底部栏:新增入口必须同时把它算进列数,否则会挤掉一个。 - Assert.Contains("Columns=\"5\"", rootView, StringComparison.Ordinal); - - var navigation = File.ReadAllText(GetRepositoryPath("SecRandom/Views/Mobile/MobileNavigation.cs")); - Assert.Contains("main.remoteDraw", navigation, StringComparison.Ordinal); - Assert.Contains("RemoteDraw", navigation, StringComparison.Ordinal); - Assert.Contains("RemoteDraw =", navigation, StringComparison.Ordinal); - - var app = File.ReadAllText(GetRepositoryPath("SecRandom/App.axaml.cs")); - Assert.Contains("MobilePageIds.RemoteDraw", app, StringComparison.Ordinal); - Assert.Contains("MobileRemoteDrawViewModel", app, StringComparison.Ordinal); - // 控制面客户端与 Bearer 边界必须注册在共享分支(桌面与手机同一条授权通道)。 - Assert.Contains("IControlPlaneClient", app, StringComparison.Ordinal); - Assert.Contains("IAuthorizedApiSender", app, StringComparison.Ordinal); - } - - [Fact] - public void 接线_页面把设备列表选中态与空态都绑上了() - { - var page = File.ReadAllText(GetRepositoryPath("SecRandom/Views/Mobile/MobileRemoteDrawPage.axaml")); - - Assert.Contains("ViewModel.Devices", page, StringComparison.Ordinal); - Assert.Contains("ViewModel.SelectedDevice", page, StringComparison.Ordinal); - Assert.Contains("ViewModel.DeviceSummary", page, StringComparison.Ordinal); - Assert.Contains("ViewModel.EmptyStateText", page, StringComparison.Ordinal); - Assert.Contains("ViewModel.UnavailableGroups", page, StringComparison.Ordinal); - Assert.Contains("ViewModel.DrawCommand", page, StringComparison.Ordinal); - } - - // ---------------------------------------------------------------- 四种状态的区分 - - /// - /// "失败"绝不能被渲染成"空数据"。 - /// - /// - /// 线上就是这一条出的问题:按组拉节点的请求拿了 404,页面却显示 - /// 「这些组里还没有设备。教室机需要用同一个账号登录,并加入本组」—— - /// 用户看到的是"没有设备",而事实是"请求失败了"。 - /// - [Fact] - public void 状态区分_请求失败时说的是失败原因而不是没有设备() - { - var failure = string.Format(LR.RD_FailureWithCode, LR.RD_NotFound, "http_404"); - - var text = MobileRemoteDrawViewModel.ResolveEmptyState( - isSignedIn: true, - isLoading: false, - hasDevices: false, - loadFailure: failure, - failedGroupCount: 0, - unavailableReason: null, - roleHint: null, - hasRoster: false); - - Assert.Equal(failure, text); - Assert.DoesNotContain(LR.RD_NoDevicesHint, text, StringComparison.Ordinal); - Assert.Contains("http_404", text, StringComparison.Ordinal); - } - - [Fact] - public void 状态区分_未登录时说的是未登录而不是没有设备() - { - var text = MobileRemoteDrawViewModel.ResolveEmptyState( - isSignedIn: false, - isLoading: false, - hasDevices: false, - loadFailure: null, - failedGroupCount: 0, - unavailableReason: null, - roleHint: null, - hasRoster: false); - - Assert.Equal(LR.RD_SignedOut, text); - } - - [Fact] - public void 状态区分_组读失败与组里没有设备是两件事() - { - // 有组读失败、且一台设备都没读到:必须说"有 N 个组没读到"。 - var failed = MobileRemoteDrawViewModel.ResolveEmptyState( - isSignedIn: true, - isLoading: false, - hasDevices: false, - loadFailure: null, - failedGroupCount: 2, - unavailableReason: null, - roleHint: null, - hasRoster: false); - - Assert.Equal(string.Format(LR.RD_GroupsUnavailable, 2), failed); - Assert.DoesNotContain(LR.RD_NoDevicesHint, failed, StringComparison.Ordinal); - - // 真的读到 0 台设备(200 + 空数组)才是"还没有设备"。 - var empty = MobileRemoteDrawViewModel.ResolveEmptyState( - isSignedIn: true, - isLoading: false, - hasDevices: false, - loadFailure: null, - failedGroupCount: 0, - unavailableReason: null, - roleHint: null, - hasRoster: false); - - Assert.Equal(LR.RD_NoDevicesHint, empty); - } - - [Fact] - public void 状态区分_网络不可达有自己的说法() - { - var text = ControlPlaneMessages.DescribeWithCode( - new ControlPlaneException("network_error", ControlPlaneErrorKind.Network)); - - Assert.Equal(LR.RD_Network, text); - } - - [Fact] - public void 状态区分_失败文案带上服务端错误码但未登录不带() - { - var notFound = ControlPlaneMessages.DescribeWithCode( - new ControlPlaneException("http_404", ControlPlaneErrorKind.NotFound)); - var unauthorized = ControlPlaneMessages.DescribeWithCode( - new ControlPlaneException("not_signed_in", ControlPlaneErrorKind.Unauthorized)); - - Assert.Contains("http_404", notFound, StringComparison.Ordinal); - Assert.Equal(LR.RD_Unauthorized, unauthorized); - } - - // ---------------------------------------------------------------- 抽取结果文案(线上回归) - - [Fact] - public void 抽取成功时必须显示抽到谁而不是沿用上一次的失败文案() - { - var command = new NodeCommandDto - { - CommandId = "cmd_1", - Status = "completed", - ResultDetail = JsonDocument.Parse( - """{ "target": "roll_call", "list_name": "测试 1", "count": 1, "drawn": [ { "id": "12", "name": "学生12" } ] }""") - .RootElement.Clone() - }; - - var text = ControlPlaneMessages.DescribeDrawResult(command); - - Assert.Equal(string.Format(LR.RD_DrawnCount, 1), text); - Assert.DoesNotContain(LR.RD_NoCandidate, text, StringComparison.Ordinal); - Assert.DoesNotContain(LR.RD_Failed, text, StringComparison.Ordinal); - } - - [Fact] - public void 抽取成功但回执没有成员时说的是回执问题而不是没人可抽() - { - var command = new NodeCommandDto - { - CommandId = "cmd_1", - Status = "completed", - ResultDetail = JsonDocument.Parse("""{ "target": "roll_call", "count": 0 }""").RootElement.Clone() - }; - - var text = ControlPlaneMessages.DescribeDrawResult(command); - - // 只有设备**明确**说没人时才可以显示"没有符合条件的人"。 - Assert.Equal(LR.RD_ResultUnreadable, text); - Assert.DoesNotContain(LR.RD_NoCandidate, text, StringComparison.Ordinal); - Assert.DoesNotContain(LR.RD_NoRosterCandidate, text, StringComparison.Ordinal); - } - - [Fact] - public void 设备说的没人可抽要带上原始错误码并且两种没人分开() - { - var noMatching = ControlPlaneMessages.DescribeDrawResult( - FailedCommand("invalid_value:gender:no_matching_member")); - var noCandidate = ControlPlaneMessages.DescribeDrawResult( - FailedCommand("invalid_value:list_name:no_candidate")); - - Assert.Contains(LR.RD_NoCandidate, noMatching, StringComparison.Ordinal); - Assert.Contains("invalid_value:gender:no_matching_member", noMatching, StringComparison.Ordinal); - - // "名单里没有可抽的人"与"条件筛完没有人"是两件事,不能共用一句文案。 - Assert.Contains(LR.RD_NoRosterCandidate, noCandidate, StringComparison.Ordinal); - Assert.NotEqual(LR.RD_NoCandidate, LR.RD_NoRosterCandidate); - } - - // ---------------------------------------------------------------- 置前决策 - - [Theory] - // 隐藏 → 显示;最小化 → 还原;已可见 → 只激活。 - [InlineData(false, false, false, true)] - [InlineData(true, true, true, false)] - [InlineData(true, false, false, false)] - public void 远程抽取提示窗口要还原显示并激活(bool isVisible, bool isMinimized, bool restore, bool show) - { - var plan = RemoteDrawWindowPlan.Resolve(isVisible, isMinimized); - - Assert.Equal(restore, plan.Restore); - Assert.Equal(show, plan.Show); - Assert.True(plan.Activate); - } - - [Fact] - public void 接线_抽取页不再重复显示标题() - { - var page = File.ReadAllText(GetRepositoryPath("SecRandom/Views/Mobile/MobileRemoteDrawPage.axaml")); - - // 页面内那个粗体大标题已被删掉:标题只由导航栏出(MobileRootView.Header)。 - Assert.DoesNotContain("langs:Resources.P_RemoteDraw", page, StringComparison.Ordinal); - // 说明行保留,并且带一点上边距,免得删掉标题后顶着导航栏。 - Assert.Contains("langs:Resources.RD_Hint", page, StringComparison.Ordinal); - Assert.Contains("Margin=\"0 4 0 0\"", page, StringComparison.Ordinal); - - // 导航栏仍然用 P_RemoteDraw,因此这个键不能删(N_RemoteDraw 是底部入口的标签)。 - var rootView = File.ReadAllText(GetRepositoryPath("SecRandom/Views/Mobile/MobileRootView.cs")); - Assert.Contains("LR.P_RemoteDraw", rootView, StringComparison.Ordinal); - } - - // ---------------------------------------------------------------- 三语覆盖 - - [Fact] - public void 三语覆盖_页面与视图模型用到的每个键在三种语言里都有值() - { - var keys = new HashSet(StringComparer.Ordinal); - - foreach (var reference in new[] - { - @"SecRandom/Views/Mobile/MobileRemoteDrawPage.axaml", - @"SecRandom/Views/Mobile/Settings/MobileSettingsCatalogPage.axaml", - @"SecRandom/ViewModels/Mobile/MobileRemoteDrawViewModel.cs", - @"SecRandom/ViewModels/Mobile/MobileAccountSectionViewModel.cs", - @"SecRandom/ViewModels/Mobile/DeviceRow.cs", - @"SecRandom/ViewModels/Mobile/RosterOption.cs", - @"SecRandom/Services/ControlPlane/ControlPlaneMessages.cs" - }) - { - var text = File.ReadAllText(GetRepositoryPath(reference)); - foreach (Match match in Regex.Matches(text, @"(?:Resources|LR)\.([A-Za-z0-9_]+)")) - keys.Add(match.Groups[1].Value); - } - - Assert.NotEmpty(keys); - - foreach (var culture in new[] { "zh-CN", "en-US", "ja-JP" }) - { - var info = new CultureInfo(culture); - foreach (var key in keys) - { - // 缺一个键,界面上就是一处空白(或退回中文),而这是只有用户会看到的问题。 - Assert.False( - string.IsNullOrWhiteSpace(LR.ResourceManager.GetString(key, info)), - $"移动端抽取页缺少 {culture} 的文案:{key}"); - } - } - } - - private static string Expected(string key) => key switch - { - "RD_MissingRosterCapability" => LR.RD_MissingRosterCapability, - "RD_MissingDrawCapability" => LR.RD_MissingDrawCapability, - "RD_ListNotFound" => LR.RD_ListNotFound, - "RD_NotInList" => LR.RD_NotInList, - "RD_OutOfRange" => LR.RD_OutOfRange, - "RD_NoCandidate" => LR.RD_NoCandidate, - "RD_NoRosterCandidate" => LR.RD_NoRosterCandidate, - "RD_InvalidValueField" => LR.RD_InvalidValueField, - _ => throw new ArgumentOutOfRangeException(nameof(key), key, null) - }; - - private static DeviceRow Row(GroupDto group, NodeDto node) => new(group, node); - - /// 一条失败的命令回执: 是控制面记录的失败原因码。 - /// 失败原因码。 - /// 取值类失败时的字段名;给了就会带上对应细因。 - /// 取值类失败时的细因。 - private static NodeCommandDto FailedCommand(string? error, string? field = null, string? why = null) - { - Dictionary? detail = null; - if (field is not null || why is not null) - { - detail = []; - if (field is not null) - detail["field"] = field; - if (why is not null) - detail["why"] = why; - } - - return new NodeCommandDto - { - CommandId = "cmd_1", - Status = "failed", - Error = error, - ResultDetail = detail is null - ? null - : JsonSerializer.SerializeToElement(detail, ControlProtocolJson.Options) - }; - } - - /// 同上,但详情直接给一个对象(例如 new { reason = "blocked_by_class_time" })。 - private static NodeCommandDto FailedCommand(string? error, object detail) => new() - { - CommandId = "cmd_1", - Status = "failed", - Error = error, - ResultDetail = JsonSerializer.SerializeToElement(detail, ControlProtocolJson.Options) - }; - - // ---------------------------------------------------------------- 抽取类型切换(点名 / 抽奖) - - [Fact] - public void 切换类型_抽奖读的是奖池并且没有性别分组() - { - var (viewModel, client) = CreateViewModel(); - - Assert.False(viewModel.IsLotteryTarget); - Assert.Equal(LR.RD_List, viewModel.ListFieldLabel); - - viewModel.SelectedDrawKind = LotteryKind; - client.Responder = request => request.Capability == ControlCapabilities.RosterRead - ? RosterCommand(PrizesResponse("元旦抽奖")) - : Completed(); - - viewModel.LoadRosterCommand.Execute(null); - - // 数据源换了:点名叫 roster.read 读 students,抽奖要读 prizes。 - Assert.Equal(ControlCapabilities.RosterRead, client.LastSubmission.Capability); - Assert.Equal( - ControlRosterReadRequest.Prizes, - client.LastSubmission.Payload!.Value.GetProperty("roster_kind").GetString()); - - Assert.True(viewModel.IsLotteryTarget); - Assert.Equal(LR.RD_Pool, viewModel.ListFieldLabel); - // 抽奖没有性别/分组:那两块整块隐藏,并且有一句解释。 - Assert.False(viewModel.IsScopeSelectorVisible); - Assert.True(viewModel.IsLotteryScopeHintVisible); - } - - [Fact] - public void 切换类型_切回点名时恢复名单与条件() - { - var (viewModel, client) = CreateViewModel(); - viewModel.SelectedDrawKind = LotteryKind; - client.Responder = _ => RosterCommand(PrizesResponse("元旦抽奖")); - viewModel.LoadRosterCommand.Execute(null); - Assert.True(viewModel.HasRoster); - - client.Responder = _ => RosterCommand(StudentsResponse("高一(1)班")); - viewModel.SelectedDrawKind = RollCallKind; - // 换类型=换一批数据:上一类的名单不能留着(否则发出去的是另一批文件里的名字)。 - Assert.False(viewModel.IsLotteryTarget); - Assert.Equal(LR.RD_List, viewModel.ListFieldLabel); - } - - [Fact] - public void 抽取_抽奖下发lottery且不带性别分组() - { - var (viewModel, client) = CreateViewModel(); - viewModel.SelectedDrawKind = LotteryKind; - client.Responder = request => request.Capability switch - { - ControlCapabilities.RosterRead => RosterCommand(PrizesResponse("元旦抽奖")), - _ => DrawnCommand("lottery", "元旦抽奖", 2) - }; - - viewModel.LoadRosterCommand.Execute(null); - viewModel.SelectedCount = 2; - viewModel.DrawCommand.Execute(null); - - Assert.Equal(ControlCapabilities.DrawTrigger, client.LastSubmission.Capability); - var payload = client.LastSubmission.Payload!.Value; - Assert.Equal("lottery", payload.GetProperty("target").GetString()); - Assert.Equal("元旦抽奖", payload.GetProperty("list_name").GetString()); - Assert.Equal(2, payload.GetProperty("count").GetInt32()); - - // 设备侧对抽奖载荷里的 gender/group 是"存在即拒绝",所以这里必须**根本不发**这两个键。 - Assert.False(payload.TryGetProperty("gender", out _)); - Assert.False(payload.TryGetProperty("group", out _)); - - Assert.Equal(2, viewModel.DrawnMembers.Count); - Assert.Equal(string.Format(LR.RD_DrawnPrizeCount, 2), viewModel.StatusText); - } - - [Fact] - public void 抽取_点名仍然带性别与分组且用roll_call目标() - { - var (viewModel, client) = CreateViewModel(); - client.Responder = request => request.Capability switch - { - ControlCapabilities.RosterRead => RosterCommand(StudentsResponse("高一(1)班")), - _ => DrawnCommand("roll_call", "高一(1)班", 2) - }; - - viewModel.LoadRosterCommand.Execute(null); - viewModel.SelectedGender = "男"; - viewModel.DrawCommand.Execute(null); - - var payload = client.LastSubmission.Payload!.Value; - Assert.Equal("roll_call", payload.GetProperty("target").GetString()); - Assert.Equal("男", payload.GetProperty("gender").GetString()); - Assert.Equal(LR.RD_Any, viewModel.SelectedGroupScope); - // "不限"不下发:协议里"没有这个字段"就是不限,发一个"不限"只会让设备去名单里找一个叫"不限"的分组。 - Assert.Equal(string.Format(LR.RD_DrawnCount, 2), viewModel.StatusText); - } - - // ---------------------------------------------------------------- 重置本轮 - - [Fact] - public void 重置_要按两次才真正下发且第二次才带目标与名单() - { - var (viewModel, client) = CreateViewModel(); - client.Responder = request => request.Capability switch - { - ControlCapabilities.RosterRead => RosterCommand(StudentsResponse("高一(1)班")), - ControlCapabilities.DrawReset => ResetCommand(3), - _ => DrawnCommand("roll_call", "高一(1)班", 1) - }; - - viewModel.LoadRosterCommand.Execute(null); - viewModel.DrawCommand.Execute(null); - Assert.True(viewModel.HasResult); - - viewModel.ResetRoundCommand.Execute(null); - // 第一次点击只是把它变成"再点一次确认":破坏性动作不该一次误触就生效。 - Assert.True(viewModel.IsResetConfirmPending); - Assert.Equal(LR.RD_ResetConfirm, viewModel.ResetButtonText); - Assert.Equal(ControlCapabilities.DrawTrigger, client.LastSubmission.Capability); - - viewModel.ResetRoundCommand.Execute(null); - - Assert.False(viewModel.IsResetConfirmPending); - Assert.Equal(LR.RD_Reset, viewModel.ResetButtonText); - var reset = client.LastSubmissionOf(ControlCapabilities.DrawReset); - var payload = reset.Payload!.Value; - Assert.Equal("roll_call", payload.GetProperty("target").GetString()); - Assert.Equal("高一(1)班", payload.GetProperty("list_name").GetString()); - - // 成功之后:清掉"抽到了谁",并用回执里的 cleared 条数显示结果。 - Assert.False(viewModel.HasResult); - Assert.Equal(string.Format(LR.RD_ResetDone, 3), viewModel.StatusText); - // 重置之后要重读名单:设备已经把这一轮的进度清零了,页面上的计数得跟着刷新。 - Assert.Equal(ControlCapabilities.RosterRead, client.LastSubmission.Capability); - } - - [Fact] - public void 重置_抽奖时清的是奖品进度而不是点名进度() - { - var (viewModel, client) = CreateViewModel(); - viewModel.SelectedDrawKind = LotteryKind; - client.Responder = request => request.Capability switch - { - ControlCapabilities.RosterRead => RosterCommand(PrizesResponse("元旦抽奖")), - ControlCapabilities.DrawReset => ResetCommand(0), - _ => DrawnCommand("lottery", "元旦抽奖", 1) - }; - - viewModel.LoadRosterCommand.Execute(null); - viewModel.ResetRoundCommand.Execute(null); - viewModel.ResetRoundCommand.Execute(null); - - var payload = client.LastSubmissionOf(ControlCapabilities.DrawReset).Payload!.Value; - Assert.Equal("lottery", payload.GetProperty("target").GetString()); - Assert.Equal("元旦抽奖", payload.GetProperty("list_name").GetString()); - Assert.Equal(string.Format(LR.RD_ResetDone, 0), viewModel.StatusText); - } - - [Fact] - public void 重置_别的动作会取消待确认状态() - { - var (viewModel, client) = CreateViewModel(); - client.Responder = _ => RosterCommand(StudentsResponse("高一(1)班")); - viewModel.LoadRosterCommand.Execute(null); - - viewModel.ResetRoundCommand.Execute(null); - Assert.True(viewModel.IsResetConfirmPending); - - // 用户改主意去了别的名单:几秒钟前那个"确认"代表的意图已经不成立了。 - viewModel.SelectedDrawKind = LotteryKind; - - Assert.False(viewModel.IsResetConfirmPending); - Assert.Equal(LR.RD_Reset, viewModel.ResetButtonText); - } - - [Fact] - public void 重置_设备侧失败时说失败原因而不是重置成功() - { - var (viewModel, client) = CreateViewModel(); - client.Responder = request => request.Capability switch - { - ControlCapabilities.RosterRead => RosterCommand(StudentsResponse("高一(1)班")), - _ => FailedCommand("busy") - }; - - viewModel.LoadRosterCommand.Execute(null); - viewModel.ResetRoundCommand.Execute(null); - viewModel.ResetRoundCommand.Execute(null); - - Assert.Contains("busy", viewModel.StatusText, StringComparison.Ordinal); - Assert.DoesNotContain(LR.RD_ResetDone.Split('{')[0], viewModel.StatusText, StringComparison.Ordinal); - } - - // ---------------------------------------------------------------- 本机标识与结果空态 - - [Theory] - [InlineData("node-1", "node-1", true)] - [InlineData("node-1", "NODE-1", true)] // 大小写不同不是两台机器 - [InlineData(" node-1 ", "node-1", true)] // 首尾空白同理 - [InlineData("node-1", "node-2", false)] - [InlineData("", "node-1", false)] // 本机身份没配置:一台都不标 - [InlineData(" ", "node-1", false)] - [InlineData("node-1", "", false)] - [InlineData("node-1", null, false)] - [InlineData(null, null, false)] - public void 本机标识_按nodeid比对且容忍大小写与空白(string? ownNodeId, string? candidateNodeId, bool expected) => - Assert.Equal(expected, DeviceRow.IsSameNode(ownNodeId, candidateNodeId)); - - [Fact] - public void 本机标识_只有本机那一行带徽章文案() - { - var self = Row("n1", isSelf: true); - var other = Row("n2"); - - // 本机**留在列表里**(只是标出来):藏起来会让人以为设备没连上,也没法给它下发命令。 - Assert.True(self.IsSelf); - Assert.Equal(LR.RD_SelfBadge, self.SelfBadgeText); - - Assert.False(other.IsSelf); - Assert.Equal(string.Empty, other.SelfBadgeText); - } - - [Fact] - public void 本机提示_只在选中本机时出现() - { - var (viewModel, _) = CreateViewModel(); - - viewModel.SelectedDevice = Row("n2"); - Assert.False(viewModel.IsSelfSelected); - - viewModel.SelectedDevice = Row("n1", isSelf: true); - Assert.True(viewModel.IsSelfSelected); - - // 提示文案来自共享 VM,两个视图都绑它。 - Assert.False(string.IsNullOrWhiteSpace(MobileRemoteDrawViewModel.SelfSelectedHint)); - } - - [Fact] - public void 结果空态_两行文案非空且出现回执后不再显示() - { - var (viewModel, _) = CreateViewModel(); - - Assert.False(string.IsNullOrWhiteSpace(MobileRemoteDrawViewModel.ResultPlaceholderTitle)); - Assert.False(string.IsNullOrWhiteSpace(MobileRemoteDrawViewModel.ResultPlaceholderHint)); - Assert.False(viewModel.HasResult); - - viewModel.DrawnMembers.Add(new NodeCommandDrawnMember("01", "张三")); - - Assert.True(viewModel.HasResult); - Assert.Contains("1", viewModel.DrawnCountText, StringComparison.Ordinal); - } - - private static DeviceRow Row(string nodeId, bool isSelf = false, bool supportsConditions = false) => new( - new GroupDto { GroupId = "g1", Name = "高一(1)班", Role = "admin" }, - new NodeDto - { - NodeId = nodeId, - DisplayName = nodeId, - Online = true, - LocalRemoteAllowed = true, - Capabilities = supportsConditions - ? [ControlCapabilities.DrawTrigger, ControlCapabilities.RosterRead, ControlCapabilities.DrawTriggerConditions] - : [ControlCapabilities.DrawTrigger, ControlCapabilities.RosterRead] - }, - isSelf); - - // ---------------------------------------------------------------- 设备加载态("已读到却仍显示正在读取设备"的回归) - - [Fact] - public async Task 加载态_成功后清掉并且不再显示加载文案() - { - var (viewModel, client) = await CreateSignedInViewModelAsync(); - client.GroupsAsync = () => Task.FromResult>([Group("g1")]); - client.NodesAsync = _ => Task.FromResult>([Node("n1")]); - - await viewModel.RefreshCommand.ExecuteAsync(null); - - // 这三条一起才说明"读完了":布尔清掉、文案不再挂着、列表真的有东西。 - Assert.False(viewModel.IsLoadingDevices); - Assert.DoesNotContain(LR.RD_LoadingDevices, viewModel.StatusText, StringComparison.Ordinal); - Assert.Single(viewModel.Devices); - } - - [Fact] - public async Task 加载态_失败后清掉并保留失败原因() - { - var (viewModel, client) = await CreateSignedInViewModelAsync(); - client.GroupsAsync = () => Task.FromException>( - new ControlPlaneException("network_error", ControlPlaneErrorKind.Network)); - - await viewModel.RefreshCommand.ExecuteAsync(null); - - Assert.False(viewModel.IsLoadingDevices); - Assert.NotEmpty(viewModel.LoadFailure); - Assert.DoesNotContain(LR.RD_LoadingDevices, viewModel.StatusText, StringComparison.Ordinal); - } - - [Fact] - public async Task 加载态_零台设备时清掉并落到空态() - { - var (viewModel, client) = await CreateSignedInViewModelAsync(); - client.GroupsAsync = () => Task.FromResult>([Group("g1")]); - // 默认 nodes 为空:组读到了,但组里没有设备。 - - await viewModel.RefreshCommand.ExecuteAsync(null); - - Assert.False(viewModel.IsLoadingDevices); - Assert.Empty(viewModel.Devices); - Assert.Equal(LR.RD_NoDevicesHint, viewModel.EmptyStateText); - Assert.DoesNotContain(LR.RD_LoadingDevices, viewModel.StatusText, StringComparison.Ordinal); - } - - [Fact] - public async Task 加载态_被更新的请求取代时旧请求不清新请求的状态() - { - var (viewModel, client) = await CreateSignedInViewModelAsync(); - var firstGate = new TaskCompletionSource>(TaskCreationOptions.RunContinuationsAsynchronously); - var calls = 0; - - client.GroupsAsync = () => Interlocked.Increment(ref calls) == 1 - ? firstGate.Task - : Task.FromResult>([Group("g1")]); - client.NodesAsync = _ => Task.FromResult>([Node("n1")]); - - // 旧请求卡住;新请求(换设备/切类型/再点刷新都会走这条路)立刻跑完。 - var stale = viewModel.RefreshCommand.ExecuteAsync(null); - var fresh = viewModel.RefreshCommand.ExecuteAsync(null); - await fresh; - - Assert.False(viewModel.IsLoadingDevices); - Assert.Single(viewModel.Devices); - - // 旧请求这时才回来:它既不许改回设备列表,也不许把新请求的加载态/状态行动掉。 - firstGate.SetResult([Group("g9")]); - await stale; - - Assert.False(viewModel.IsLoadingDevices); - Assert.DoesNotContain(LR.RD_LoadingDevices, viewModel.StatusText, StringComparison.Ordinal); - Assert.Single(viewModel.Devices); - Assert.Equal("n1", viewModel.Devices[0].NodeId); - } - - /// - /// 建一个**已登录**的 VM。 - /// - /// - /// 设备加载路径在未登录时会直接早退(那是对的:没登录就没有组可读), - /// 因此要测加载态就必须先有一对令牌。 - /// - private async Task<(MobileRemoteDrawViewModel ViewModel, RecordingControlPlaneClient Client)> CreateSignedInViewModelAsync() - { - var configHandler = new MainConfigHandler( - NullLogger.Instance, - new TestConfigService(new MainConfigModel())); - var tokenStore = TestTokenStore.Create(); - await tokenStore.SaveAsync(new SectlToken("access", "refresh", "user-1", 3600), CancellationToken.None); - - var auth = new SectlAuthService( - tokenStore, - new StubHttpClientFactory(new HttpClient()), - new DeviceUuidStore(configHandler, NullLogger.Instance), - NullLogger.Instance, - new LoopbackAuthRedirectBrokerFactory()); - await auth.InitializeAsync(); - - var client = new RecordingControlPlaneClient(); - var viewModel = new MobileRemoteDrawViewModel( - configHandler, - client, - new FileControlPlaneDevicePreferenceStore(_preferencePath), - auth, - NullLogger.Instance); - - return (viewModel, client); - } - - /// - /// 建一个"接入了自建集控"的 VM,默认**未登录 SECTL**——正是"手机不登录也能用"的那个场景。 - /// - private (MobileRemoteDrawViewModel ViewModel, RecordingControlPlaneClient Client, FakeEnrollmentStore Store) - CreateEnrolledViewModel(bool enrolled = true, bool expired = false, bool unreadable = false) - { - var configHandler = new MainConfigHandler( - NullLogger.Instance, - new TestConfigService(new MainConfigModel())); - var auth = new SectlAuthService( - TestTokenStore.Create(), - new StubHttpClientFactory(new HttpClient()), - new DeviceUuidStore(configHandler, NullLogger.Instance), - NullLogger.Instance, - new LoopbackAuthRedirectBrokerFactory()); - - var store = new FakeEnrollmentStore(); - if (enrolled || expired) - { - store.Save(new NodeEnrollmentRecord - { - NodeId = "node-1", - GroupId = "g1", - NodeToken = "srn_test_token", - ExpiresAt = expired ? DateTimeOffset.UtcNow.AddMinutes(-1) : DateTimeOffset.UtcNow.AddDays(30) - }); - } - - if (unreadable) - store.MarkUnreadable(); - - var client = new RecordingControlPlaneClient(); - var viewModel = new MobileRemoteDrawViewModel( - configHandler, - client, - new FileControlPlaneDevicePreferenceStore(_preferencePath), - auth, - NullLogger.Instance, - nodeStateStore: null, - enrollmentStore: store); - - return (viewModel, client, store); - } - - /// - /// 建一个"手机端就地接入"的 VM:接入客户端、基址存储、真实平台名与设备名都接上,默认**未接入**。 - /// - /// - /// 手机没有本地节点(nodeStateStore: null),接入时 node_id 整帧缺席、平台名报 android。 - /// - private ( - MobileRemoteDrawViewModel ViewModel, - RecordingControlPlaneClient Client, - FakeEnrollmentStore Store, - FakeEndpointStore Endpoint) CreateEnrollingViewModel( - RecordingEnrollHandler? handler = null, - bool enrolled = false, - bool customEndpoint = false) - { - var configHandler = new MainConfigHandler( - NullLogger.Instance, - new TestConfigService(new MainConfigModel())); - var auth = new SectlAuthService( - TestTokenStore.Create(), - new StubHttpClientFactory(new HttpClient()), - new DeviceUuidStore(configHandler, NullLogger.Instance), - NullLogger.Instance, - new LoopbackAuthRedirectBrokerFactory()); - - var endpoint = new FakeEndpointStore("https://control.example", customEndpoint); - var store = new FakeEnrollmentStore(); - if (enrolled) - { - store.Save(new NodeEnrollmentRecord - { - NodeId = "node-1", - GroupId = "g1", - NodeToken = "srn_test_token", - ExpiresAt = DateTimeOffset.UtcNow.AddDays(30) - }); - } - - var client = new RecordingControlPlaneClient(); - var viewModel = new MobileRemoteDrawViewModel( - configHandler, - client, - new FileControlPlaneDevicePreferenceStore(_preferencePath), - auth, - NullLogger.Instance, - nodeStateStore: null, - enrollmentStore: store, - enrollmentClient: new NodeEnrollmentClient( - new FakeHttpClientFactory( - handler ?? new RecordingEnrollHandler(_ => Json(HttpStatusCode.OK, EnrollOk()))), - endpoint), - endpointStore: endpoint, - platform: "android", - deviceName: "Pixel 7"); - - return (viewModel, client, store, endpoint); - } - - // ---------------------------------------------------------------- 抽奖条件集(draw.trigger.conditions) - - [Fact] - public void 条件集_设备没声明能力时绝不发conditions() - { - var (viewModel, client) = CreateViewModel(); - viewModel.SelectedDrawKind = LotteryKind; - viewModel.SelectedDevice = Row("n1", supportsConditions: false); - - // 就算界面上残留了条件(换设备、旧状态),也**不许**把它们发出去: - // 老设备会把 conditions 当"没写"从而静默按整池抽,那正是红线。 - viewModel.SelectedRecipientList = "高一(1)班"; - viewModel.SelectedPrizeTags.Add(new PrizeTagOption("文具")); - - Assert.False(viewModel.SupportsDrawConditions); - Assert.False(viewModel.ShowsLotteryConditions); - Assert.True(viewModel.ShowsLotteryConditionsUnsupported); - - client.Responder = request => request.Capability switch - { - ControlCapabilities.RosterRead => RosterCommand(PrizesResponse("元旦抽奖")), - _ => DrawnCommand("lottery", "元旦抽奖", 1) - }; - viewModel.LoadRosterCommand.Execute(null); - viewModel.DrawCommand.Execute(null); - - var payload = client.LastSubmission.Payload!.Value; - Assert.False(payload.TryGetProperty("conditions", out _)); - } - - [Fact] - public void 条件集_声明了能力的抽奖设备会带上标签与发放名单() - { - var (viewModel, client) = CreateViewModel(); - viewModel.SelectedDrawKind = LotteryKind; - - client.Responder = request => request.Capability switch - { - ControlCapabilities.RosterRead => RosterCommand(PrizesResponse("元旦抽奖")), - _ => DrawnCommand("lottery", "元旦抽奖", 1) - }; - viewModel.SelectedDevice = Row("n1", supportsConditions: true); - Assert.True(viewModel.ShowsLotteryConditions); - - viewModel.LoadRosterCommand.Execute(null); - viewModel.SelectedPrizeTags.Add(new PrizeTagOption("一等奖")); - viewModel.SelectedRecipientList = "高一(1)班"; - viewModel.DrawCommand.Execute(null); - - var payload = client.LastSubmission.Payload!.Value; - var conditions = payload.GetProperty("conditions"); - Assert.Equal(1, conditions.GetProperty("version").GetInt32()); - Assert.Equal("一等奖", conditions.GetProperty("prize_tags")[0].GetString()); - Assert.Equal("高一(1)班", conditions.GetProperty("student_list").GetString()); - - // 顶层 gender/group 对抽奖仍然**根本不发**(设备侧是"存在即拒绝")。 - Assert.False(payload.TryGetProperty("gender", out _)); - Assert.False(payload.TryGetProperty("group", out _)); - } - - private static GroupDto Group(string groupId) => new() { GroupId = groupId, Name = groupId, Role = "admin" }; - - // ---------------------------------------------------------------- 未登录 SECTL 也能用(已接入自建集控) - - /// - /// 这一条就是整个功能的用户价值:**没登录 SECTL,只要接入了自建集控,设备照样读得到**。 - /// - [Fact] - public async Task 接入_未登录但已接入时设备照样读得到且不再提示登录() - { - var (viewModel, client, _) = CreateEnrolledViewModel(); - client.GroupsAsync = () => Task.FromResult>([Group("g1")]); - client.NodesAsync = _ => Task.FromResult>([Node("n1")]); - - await viewModel.InitializeAsync(); - - Assert.False(viewModel.IsSignedIn); - Assert.True(viewModel.IsEnrolled); - Assert.True(viewModel.HasControlPlaneAccess); - Assert.False(viewModel.NeedsSignIn); - Assert.Single(viewModel.Devices); - Assert.DoesNotContain(LR.RD_SignedOut, viewModel.EmptyStateText, StringComparison.Ordinal); - } - - [Fact] - public async Task 接入_未接入且未登录时还是原来那句提示并且不发注定失败的请求() - { - var groupsCalls = 0; - var (viewModel, client, _) = CreateEnrolledViewModel(enrolled: false); - client.GroupsAsync = () => - { - Interlocked.Increment(ref groupsCalls); - return Task.FromResult>([Group("g1")]); - }; - - await viewModel.RefreshCommand.ExecuteAsync(null); - - Assert.False(viewModel.IsEnrolled); - Assert.False(viewModel.HasControlPlaneAccess); - Assert.True(viewModel.NeedsSignIn); - Assert.False(viewModel.NeedsEnrollment); - Assert.Equal(LR.RD_SignedOut, viewModel.EmptyStateText); - - // 没凭据就不该去请求:那只会拿一个 401 回来,还会把"请先登录"挤掉。 - Assert.Equal(0, groupsCalls); - } - - [Fact] - public async Task 接入_记录读不出来时要求去设置填接入码而不是反复重试() - { - var (viewModel, client, _) = CreateEnrolledViewModel(unreadable: true); - client.GroupsAsync = () => Task.FromResult>([Group("g1")]); - - await viewModel.RefreshCommand.ExecuteAsync(null); - - Assert.False(viewModel.IsEnrolled); - Assert.True(viewModel.NeedsEnrollment); - Assert.True(viewModel.NeedsSignIn); - Assert.Equal(LR.RD_EnrollmentRequired, viewModel.EmptyStateText); - } - - [Fact] - public async Task 接入_服务端拒了令牌时说要重新接入而不是去登录() - { - var (viewModel, client, _) = CreateEnrolledViewModel(); - client.GroupsAsync = () => Task.FromException>( - new ControlPlaneException("unauthorized", ControlPlaneErrorKind.Unauthorized)); - - await viewModel.RefreshCommand.ExecuteAsync(null); - - Assert.True(viewModel.IsEnrolled); // 令牌还在,只是服务端不认了 - Assert.True(viewModel.EnrollmentRejected); - Assert.True(viewModel.NeedsEnrollment); - Assert.False(viewModel.NeedsSignIn); // 这时让用户去登录 SECTL 是死路 - Assert.NotEmpty(viewModel.LoadFailure); // 失败原因优先展示 - Assert.DoesNotContain(LR.RD_SignedOut, viewModel.EmptyStateText, StringComparison.Ordinal); - } - - /// 0=未登录文案,1=去设置填接入码,2=重新接入,3=还没有设备。 - [Theory] - [InlineData(false, false, false, 0)] // 未登录未接入:未登录文案 - [InlineData(false, true, false, 1)] // 未接入、需要接入:去设置填接入码 - [InlineData(true, true, true, 2)] // 已接入、被服务端拒了:重新接入 - [InlineData(true, true, false, 3)] // 已接入、本地过期但服务端没说:不误报"失效" - public void 接入_空态文案按接入优先于登录的顺序判定( - bool isEnrolled, - bool needsEnrollment, - bool enrollmentExpired, - int expected) - { - var text = MobileRemoteDrawViewModel.ResolveEmptyState( - isSignedIn: false, - isLoading: false, - hasDevices: false, - loadFailure: null, - failedGroupCount: 0, - unavailableReason: null, - roleHint: null, - hasRoster: false, - isEnrolled: isEnrolled, - needsEnrollment: needsEnrollment, - enrollmentExpired: enrollmentExpired); - - var expectedText = expected switch - { - 0 => LR.RD_SignedOut, - 1 => LR.RD_EnrollmentRequired, - 2 => LR.RD_EnrollmentExpired, - _ => LR.RD_NoDevicesHint - }; - - Assert.Equal(expectedText, text); - - if (expected != 0) - Assert.DoesNotContain(LR.RD_SignedOut, text, StringComparison.Ordinal); - } - - // ---------------------------------------------------------------- 手机端内联接入卡片 - - /// - /// 未接入(也没登录)时,手机页必须**就地**给出接入入口,而不是只留一句"去设置"。 - /// - /// - /// 手机上根本没有「设置 → 集控」那一页( 找不到页面时既不报错也不返回失败), - /// 只给导航按钮就等于给了一条走不通的路;这条用例同时钉住页面绑的是"卡片"而不是"导航"。 - /// - [Fact] - public void 接入_未接入时手机页就地给出接入入口而不是死路() - { - var (viewModel, _, _, _) = CreateEnrollingViewModel(); - - Assert.False(viewModel.IsEnrolled); - Assert.False(viewModel.HasControlPlaneAccess); - Assert.True(viewModel.ShowEnrollmentEntry); // 就地给卡片 - Assert.True(viewModel.ShowEndpointField); - Assert.False(viewModel.ShowReenrollNavigation); // 那个导航按钮收起来,不留"点了没反应" - Assert.False(viewModel.CanEnroll); // 没填接入码时按钮禁用 - Assert.False(viewModel.CanClearEnrollment); - Assert.False(viewModel.HasEnrollmentMessage); - - // 卡片本身要真的在页面里:删掉这段 XAML 等于又把入口收了回去。 - var page = File.ReadAllText(GetRepositoryPath("SecRandom/Views/Mobile/MobileRemoteDrawPage.axaml")); - Assert.Contains("ViewModel.ShowEnrollmentEntry", page, StringComparison.Ordinal); - Assert.Contains("ViewModel.ControlPlaneEndpoint", page, StringComparison.Ordinal); - Assert.Contains("ViewModel.SiteId", page, StringComparison.Ordinal); - Assert.Contains("ViewModel.EnrollmentCode", page, StringComparison.Ordinal); - Assert.Contains("ViewModel.EnrollCommand", page, StringComparison.Ordinal); - Assert.Contains("ViewModel.ClearEnrollmentCommand", page, StringComparison.Ordinal); - Assert.Contains("ViewModel.ShowReenrollNavigation", page, StringComparison.Ordinal); - Assert.DoesNotContain("IsVisible=\"{Binding ViewModel.NeedsEnrollment}\"", page, StringComparison.Ordinal); - } - - /// 没有接入存储的宿主(降级接线)不该看到一张填了也没用的卡。 - [Fact] - public void 接入_没有接入存储的宿主不显示这张卡片() - { - var (viewModel, _) = CreateViewModel(); - - Assert.False(viewModel.ShowEnrollmentEntry); - Assert.False(viewModel.ShowEndpointField); - } - - /// 填地点 ID + 配对码点"接入":换成设备凭据、清空两个输入框、并把设备列表拉起来。 - [Fact] - public async Task 接入_填入地点ID与配对码后换成设备凭据并自己刷新设备列表() - { - var handler = new RecordingEnrollHandler(_ => Json(HttpStatusCode.OK, EnrollOk())); - var (viewModel, client, store, _) = CreateEnrollingViewModel(handler); - // 页面加载(Loaded)之后卡片才可能被点到;订阅也是在这一步接上的。 - await viewModel.InitializeAsync(); - - // 接入成功后列表要跟着起来:存储的 Changed 会触发一次刷新,这里等它真的发生。 - var refreshed = new TaskCompletionSource(); - client.GroupsAsync = () => - { - refreshed.TrySetResult(); - return Task.FromResult>([Group("g1")]); - }; - - viewModel.SiteId = " sc-7k3m9q "; - viewModel.EnrollmentCode = " 7K3M-9QZX "; - Assert.True(viewModel.CanEnroll); - - await viewModel.EnrollCommand.ExecuteAsync(null); - await refreshed.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); - - Assert.True(viewModel.IsEnrolled); - Assert.Equal("第一实验学校", store.Status.SiteName); - Assert.True(store.TryGetCredential(out var credential)); - Assert.Equal("dev-9", credential!.DeviceId); - Assert.Equal("secret_9", credential.Secret); - Assert.Equal("SC-7K3M9Q", credential.SiteId); - - // 两个输入框用完即清,失败提示为空,卡片自己收起来。 - Assert.Equal(string.Empty, viewModel.SiteId); - Assert.Equal(string.Empty, viewModel.EnrollmentCode); - Assert.Equal(string.Empty, viewModel.EnrollmentMessage); - Assert.False(viewModel.ShowEnrollmentEntry); - - // 请求形状:匿名、POST 到 v4 契约里的那条路径,双因子都被规范化后再发。 - var request = Assert.Single(handler.Requests); - Assert.Equal(HttpMethod.Post, request.Method); - Assert.Equal("/control/api/enroll", request.Uri.AbsolutePath); - Assert.Null(request.Authorization); - - using var body = JsonDocument.Parse(request.Body); - Assert.Equal("SC-7K3M9Q", body.RootElement.GetProperty("siteId").GetString()); - Assert.Equal("7K3M9QZX", body.RootElement.GetProperty("code").GetString()); - Assert.Equal("Pixel 7", body.RootElement.GetProperty("deviceName").GetString()); - } - - /// 双因子缺一个都不发请求:只填地点 ID、或只填配对码,按钮是灰的,点了也不发。 - [Fact] - public async Task 接入_双因子缺一个都不发请求() - { - var handler = new RecordingEnrollHandler(_ => Json(HttpStatusCode.OK, EnrollOk())); - var (viewModel, _, store, _) = CreateEnrollingViewModel(handler); - - viewModel.SiteId = "SC-7K3M9Q"; - Assert.False(viewModel.CanEnroll); - await viewModel.EnrollCommand.ExecuteAsync(null); - - viewModel.SiteId = string.Empty; - viewModel.EnrollmentCode = "7K3M-9QZX"; - Assert.False(viewModel.CanEnroll); - await viewModel.EnrollCommand.ExecuteAsync(null); - - Assert.Equal(0, handler.Calls); - Assert.False(store.Status.HasCredential); - // 用户填的东西不能被"一次注定失败的点按"清掉。 - Assert.Equal("7K3M-9QZX", viewModel.EnrollmentCode); - } - - /// 服务端拒绝时只显示错误码,双因子输入留着让用户改一个字符重试,且**绝不回显**输入真值。 - [Fact] - public async Task 接入_服务端拒绝时只显示错误码并且双因子留着让人改() - { - var handler = new RecordingEnrollHandler(_ => - Json(HttpStatusCode.NotFound, """{"ok":false,"code":"code_not_found"}""")); - var (viewModel, _, store, _) = CreateEnrollingViewModel(handler); - - viewModel.SiteId = "SC-7K3M9Q"; - viewModel.EnrollmentCode = "ABCD-7KQ2"; - - await viewModel.EnrollCommand.ExecuteAsync(null); - - Assert.False(viewModel.IsEnrolled); - Assert.False(store.Status.HasCredential); - Assert.Equal(string.Format(LR.RD_EnrollFailed, "code_not_found"), viewModel.EnrollmentMessage); - Assert.True(viewModel.HasEnrollmentMessage); - Assert.True(viewModel.ShowEnrollmentEntry); // 卡片留着,用户能直接重填 - Assert.Equal("SC-7K3M9Q", viewModel.SiteId); - Assert.Equal("ABCD-7KQ2", viewModel.EnrollmentCode); - Assert.DoesNotContain("ABCD-7KQ2", viewModel.EnrollmentMessage, StringComparison.Ordinal); - } - - /// 基址只在点"接入"那一刻落盘(绑定的默认触发器是逐字符更新,边打边写盘是另一回事)。 - [Fact] - public async Task 接入_地址只在点接入时才落盘() - { - var handler = new RecordingEnrollHandler(_ => Json(HttpStatusCode.OK, EnrollOk())); - var (viewModel, _, _, endpoint) = CreateEnrollingViewModel(handler); - - viewModel.ControlPlaneEndpoint = "https://console.example"; - Assert.Equal(0, endpoint.UpdateCalls); - - viewModel.SiteId = "SC-7K3M9Q"; - viewModel.EnrollmentCode = "7K3M-9QZX"; - await viewModel.EnrollCommand.ExecuteAsync(null); - - Assert.Equal(1, endpoint.UpdateCalls); - Assert.Equal("https://console.example", endpoint.Current); - // 请求确实打到了刚填的那个地址上(改完地址就能用,不必重启)。 - Assert.Equal("https://console.example", Assert.Single(handler.Requests).Uri.GetLeftPart(UriPartial.Authority)); - } - - /// 地址不合法时只提示、不写盘、也不拿它去发请求。 - [Fact] - public async Task 接入_地址不合法时只提示不拿它去发请求() - { - var handler = new RecordingEnrollHandler(_ => Json(HttpStatusCode.OK, EnrollOk())); - var (viewModel, _, _, endpoint) = CreateEnrollingViewModel(handler); - endpoint.AcceptUpdate = false; - - viewModel.ControlPlaneEndpoint = "这不是一个地址"; - viewModel.SiteId = "SC-7K3M9Q"; - viewModel.EnrollmentCode = "7K3M-9QZX"; - - await viewModel.EnrollCommand.ExecuteAsync(null); - - Assert.True(viewModel.HasEndpointError); - Assert.False(viewModel.IsEnrolled); - Assert.Equal(0, handler.Calls); - Assert.Equal(string.Empty, viewModel.EnrollmentMessage); - } - - /// 清除接入后回到"未接入"的入口状态:卡片重新出现,令牌立刻读不出来。 - [Fact] - public async Task 接入_清除接入后回到未接入的入口状态() - { - var (viewModel, _, store, _) = CreateEnrollingViewModel(enrolled: true); - await viewModel.InitializeAsync(); // 页面加载之后才会有"清除接入"这个动作 - - Assert.True(viewModel.IsEnrolled); - Assert.False(viewModel.ShowEnrollmentEntry); // 已经能用,不再拿接入卡片占地方 - Assert.True(viewModel.CanClearEnrollment); - - viewModel.ClearEnrollmentCommand.Execute(null); - - Assert.False(viewModel.IsEnrolled); - Assert.False(store.TryGetAccessToken(out _)); - Assert.True(viewModel.ShowEnrollmentEntry); - Assert.False(viewModel.ShowReenrollNavigation); - Assert.Equal(string.Empty, viewModel.EnrollmentMessage); - } - - /// 基址被改成过自建的(说明在用自建集控)时,接入卡片也要给:节点令牌可能得补回来。 - [Fact] - public void 接入_自建基址下即使已接入也给入口() - { - var (viewModel, _, _, _) = CreateEnrollingViewModel(enrolled: true, customEndpoint: true); - - Assert.True(viewModel.IsEnrolled); - Assert.True(viewModel.ShowEnrollmentEntry); - Assert.False(viewModel.ShowReenrollNavigation); - } - - private static NodeDto Node(string nodeId) => new() - { - NodeId = nodeId, - DisplayName = nodeId, - Online = true, - LocalRemoteAllowed = true, - Capabilities = [ControlCapabilities.DrawTrigger, ControlCapabilities.RosterRead] - }; - - // ---------------------------------------------------------------- 测试替身 - - private static readonly RemoteDrawKindOption LotteryKind = RemoteDrawKindOption.CreateLottery(); - - private static readonly RemoteDrawKindOption RollCallKind = RemoteDrawKindOption.CreateRollCall(); - - private (MobileRemoteDrawViewModel ViewModel, RecordingControlPlaneClient Client) CreateViewModel() - { - var configHandler = new MainConfigHandler( - NullLogger.Instance, - new TestConfigService(new MainConfigModel())); - var deviceUuidStore = new DeviceUuidStore(configHandler, NullLogger.Instance); - var auth = new SectlAuthService( - TestTokenStore.Create(), - new StubHttpClientFactory(new HttpClient()), - deviceUuidStore, - NullLogger.Instance, - new LoopbackAuthRedirectBrokerFactory()); - - var client = new RecordingControlPlaneClient(); - var viewModel = new MobileRemoteDrawViewModel( - configHandler, - client, - new FileControlPlaneDevicePreferenceStore(_preferencePath), - auth, - NullLogger.Instance) - { - // 设备列表平时是网络拉回来的,这里直接选中一台可用设备:这些断言关心的是选中之后的行为。 - SelectedDevice = new DeviceRow( - new GroupDto { GroupId = "g1", Name = "高一(1)班", Role = "admin" }, - new NodeDto - { - NodeId = "n1", - DisplayName = "讲台机", - Online = true, - LocalRemoteAllowed = true, - Capabilities = [ControlCapabilities.DrawTrigger, ControlCapabilities.RosterRead] - }) - }; - - return (viewModel, client); - } - - private static NodeCommandDto RosterCommand(ControlRosterReadResponse response) => new() - { - CommandId = "cmd_roster", - Status = "completed", - ResultPayload = JsonSerializer.SerializeToElement(response, ControlProtocolJson.Options) - }; - - private static NodeCommandDto DrawnCommand(string target, string listName, int count) => new() - { - CommandId = "cmd_draw", - Status = "completed", - ResultDetail = JsonDocument.Parse( - $$""" - { "target": "{{target}}", "list_name": "{{listName}}", "count": {{count}}, - "drawn": [ { "id": "01", "name": "张三" }, { "id": "02", "name": "李四" } ] } - """).RootElement.Clone() - }; - - private static NodeCommandDto ResetCommand(int cleared) => new() - { - CommandId = "cmd_reset", - Status = "completed", - ResultDetail = JsonDocument.Parse( - $$"""{ "target": "roll_call", "list_name": "高一(1)班", "cleared": {{cleared}} }""") - .RootElement.Clone() - }; - - private static ControlRosterReadResponse StudentsResponse(string name) => new( - ControlRosterReadRequest.Students, - [ - new ControlRosterListPayload( - name, - true, - 2, - 2, - false, - [ - new ControlRosterMemberPayload("01", "张三", "男", "A组", null, null, true), - new ControlRosterMemberPayload("02", "李四", "女", "B组", null, null, true) - ]) - ]); - - private static ControlRosterReadResponse PrizesResponse(string name) => new( - ControlRosterReadRequest.Prizes, - [ - new ControlRosterListPayload( - name, - true, - 2, - 2, - false, - [ - new ControlRosterMemberPayload("P01", "一等奖", null, null, 1, 1, true), - new ControlRosterMemberPayload("P02", "二等奖", null, null, 3, 1, true) - ]) - ]); - - /// 按能力回一条固定回执的控制面客户端;同时记下最后一次下发的命令本体。 - private sealed class RecordingControlPlaneClient : IControlPlaneClient - { - public List Submissions { get; } = []; - - public Func Responder { get; set; } = _ => Completed(); - - /// 读组的行为(默认空:多数用例只关心选中设备之后的行为)。 - public Func>> GroupsAsync { get; set; } = - () => Task.FromResult>([]); - - /// 读某组设备的行为(默认空)。 - public Func>> NodesAsync { get; set; } = - _ => Task.FromResult>([]); - - public ControlPlaneCommandRequest LastSubmission => Submissions[^1]; - - /// 某条能力最后一次下发的载荷。 - /// - /// 重置成功之后还会再读一次名单,因此"最后一次下发"未必是测试关心的那条命令。 - /// - public ControlPlaneCommandRequest LastSubmissionOf(string capability) => - Submissions.Last(request => string.Equals(request.Capability, capability, StringComparison.Ordinal)); - - public Task> GetGroupsAsync(CancellationToken cancellationToken = default) => - GroupsAsync(); - - public Task> GetNodesAsync(string groupId, CancellationToken cancellationToken = default) => - NodesAsync(groupId); - - public Task SubmitCommandAsync( - string groupId, - string nodeId, - ControlPlaneCommandRequest request, - CancellationToken cancellationToken = default) - { - Submissions.Add(request); - return Task.FromResult(new NodeCommandDto { CommandId = $"cmd_{Submissions.Count}", Status = "pending" }); - } - - public Task GetCommandAsync( - string groupId, - string commandId, - CancellationToken cancellationToken = default) => - Task.FromResult(Responder(LastSubmission)); - - public Task PollCommandAsync( - string groupId, - string commandId, - ControlPlanePollOptions? options = null, - CancellationToken cancellationToken = default) => - Task.FromResult(Responder(LastSubmission)); - } - - private static NodeCommandDto Completed() => new() { CommandId = "cmd", Status = "completed" }; - - private sealed class StubHttpClientFactory(HttpClient client) : IHttpClientFactory - { - public HttpClient CreateClient(string name) => client; - } - - 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) - { - } - } - - /// 内存版接入存储:手机侧只关心"有没有接入",所以这里只要状态对得上就行。 - private sealed class FakeEnrollmentStore : INodeEnrollmentStore - { - private readonly object _gate = new(); - private NodeEnrollmentRecord? _record; - private bool _unreadable; - - public NodeEnrollmentStatus Status - { - get - { - lock (_gate) - { - if (_unreadable) - return new NodeEnrollmentStatus { IsUnreadable = true }; - - if (_record is null) - return NodeEnrollmentStatus.NotEnrolled; - - return new NodeEnrollmentStatus - { - HasToken = true, - IsExpired = _record.ExpiresAt is { } expires && expires <= DateTimeOffset.UtcNow, - NodeId = _record.NodeId, - DeviceId = _record.DeviceId, - SiteId = _record.SiteId, - SiteName = _record.SiteName, - ClassId = _record.ClassId, - ClassName = _record.ClassName, - GroupId = _record.GroupId, - GroupName = _record.GroupName, - ExpiresAt = _record.ExpiresAt - }; - } - } - } - - public int Generation { get; private set; } - - public event EventHandler? Changed; - - /// 模拟"记录读不出来":文件还在,但已经按未接入处理。 - public void MarkUnreadable() - { - lock (_gate) - { - _record = null; - _unreadable = true; - Generation++; - } - - Changed?.Invoke(this, Status); - } - - public bool TryGetAccessToken(out string? accessToken) - { - lock (_gate) - { - accessToken = _record?.NodeToken; - return _record is not null; - } - } - - /// v4 的凭据通道:手机端接入成功后存的是 deviceId/secret/siteId。 - public bool TryGetCredential(out NodeDeviceCredential? credential) - { - lock (_gate) - { - credential = _record is null - ? null - : new NodeDeviceCredential( - _record.DeviceId, - _record.Secret, - _record.SiteId, - _record.SiteName, - _record.ClassId, - _record.ClassName); - return credential is not null; - } - } - - public bool Save(NodeEnrollmentRecord record) - { - lock (_gate) - { - _record = record; - _unreadable = false; - Generation++; - } - - Changed?.Invoke(this, Status); - return true; - } - - public bool Clear() - { - bool had; - lock (_gate) - { - had = _record is not null || _unreadable; - _record = null; - _unreadable = false; - Generation++; - } - - Changed?.Invoke(this, Status); - return had; - } - } - - private static string GetRepositoryPath(string relativePath) => Path.Combine( - Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "../../../..")), - relativePath); - - // ---------------------------------------------------------------- 接入请求的假件 - - private static HttpResponseMessage Json(HttpStatusCode status, string body) => new(status) - { - Content = new StringContent(body, Encoding.UTF8, "application/json") - }; - - /// v4 契约里的成功回应:统一信封 {ok,data},设备凭据只出现这一次。 - private static string EnrollOk(string secret = "secret_9", string deviceId = "dev-9") => - $$""" - { "ok": true, "data": { "deviceId": "{{deviceId}}", "secret": "{{secret}}", - "site": { "id": "site-1", "publicId": "SC-7K3M9Q", "name": "第一实验学校" }, - "heartbeatSeconds": 25, "offlineAfterSeconds": 75, "wsPath": "/control/ws" } } - """; - - private sealed record SentEnrollRequest(HttpMethod Method, Uri Uri, string Body, string? Authorization); - - /// 接住手机端发出去的那个接入请求:方法、地址、请求体、以及"到底有没有带凭据"。 - private sealed class RecordingEnrollHandler(Func responder) - : HttpMessageHandler - { - private readonly object _gate = new(); - private readonly List _requests = []; - - public IReadOnlyList Requests - { - get - { - lock (_gate) - return [.. _requests]; - } - } - - public int Calls - { - get - { - lock (_gate) - return _requests.Count; - } - } - - protected override async Task SendAsync( - HttpRequestMessage request, - CancellationToken cancellationToken) - { - var body = request.Content is null - ? string.Empty - : await request.Content.ReadAsStringAsync(cancellationToken); - - lock (_gate) - { - _requests.Add(new SentEnrollRequest( - request.Method, - request.RequestUri!, - body, - request.Headers.Authorization?.ToString())); - } - - return responder(request); - } - } - - private sealed class FakeHttpClientFactory(HttpMessageHandler handler) : IHttpClientFactory - { - public HttpClient CreateClient(string name) => new(handler, disposeHandler: false); - } - - /// - /// 内存版基址存储:手机端"改地址再接入"这条路径要能单测。 - /// - private sealed class FakeEndpointStore : IControlPlaneEndpointStore - { - private readonly string _defaultBaseUrl; - - public FakeEndpointStore(string defaultBaseUrl, bool custom = false) - { - _defaultBaseUrl = defaultBaseUrl; - Current = defaultBaseUrl; - IsCustom = custom; - } - - public string Current { get; private set; } - - public bool IsCustom { get; private set; } - - /// false = 模拟"这个地址不合法",此时什么都不写、只回错误。 - public bool AcceptUpdate { get; set; } = true; - - public int UpdateCalls { get; private set; } - - public event EventHandler? Changed; - - public bool TryUpdate(string? endpoint, out string? error) - { - UpdateCalls++; - if (!AcceptUpdate || string.IsNullOrWhiteSpace(endpoint)) - { - error = "invalid_endpoint"; - return false; - } - - Current = endpoint.Trim(); - IsCustom = true; - error = null; - Changed?.Invoke(this, Current); - return true; - } - - public void ResetToDefault() - { - Current = _defaultBaseUrl; - IsCustom = false; - Changed?.Invoke(this, Current); - } - } -} diff --git a/SecRandom.Core.Tests/NotificationCountdownPaletteTests.cs b/SecRandom.Core.Tests/NotificationCountdownPaletteTests.cs new file mode 100644 index 000000000..cbe696df5 --- /dev/null +++ b/SecRandom.Core.Tests/NotificationCountdownPaletteTests.cs @@ -0,0 +1,157 @@ +using System.Text.Json; +using Avalonia.Media; +using SecRandom.Core.Abstraction; +using SecRandom.Core.Models.SubConfigs; + +namespace SecRandom.Core.Tests; + +public class NotificationCountdownPaletteTests +{ + [Fact] + public void DefaultsRunFromBlueToRed() + { + Assert.Equal(Color.Parse("#2E8BFF"), NotificationCountdownPalette.DefaultStart); + Assert.Equal(Color.Parse("#EF4444"), NotificationCountdownPalette.DefaultEnd); + } + + [Fact] + public void SampleHitsBothEndsAndTheMiddle() + { + var start = Color.FromArgb(255, 0, 0, 0); + var end = Color.FromArgb(255, 100, 100, 100); + + Assert.Equal(start, NotificationCountdownPalette.Sample(start, end, 0)); + Assert.Equal(end, NotificationCountdownPalette.Sample(start, end, 1)); + Assert.Equal(Color.FromArgb(255, 50, 50, 50), NotificationCountdownPalette.Sample(start, end, 0.5)); + Assert.Equal(start, NotificationCountdownPalette.Sample(start, end, -1)); + Assert.Equal(end, NotificationCountdownPalette.Sample(start, end, 2)); + } + + [Fact] + public void SampleAlwaysYieldsOpaqueColors() + { + var translucent = Color.FromArgb(10, 1, 2, 3); + + var color = NotificationCountdownPalette.Sample(translucent, translucent, 0.5); + + Assert.Equal((byte)255, color.A); + Assert.Equal((byte)1, color.R); + } + + [Fact] + public void SampleWithIdenticalEndsIsThatColor() + { + var color = Color.FromArgb(40, 1, 2, 3); + var expected = NotificationCountdownPalette.ToOpaque(color); + + Assert.Equal(expected, NotificationCountdownPalette.Sample(color, color, 0.4)); + Assert.Equal(expected, NotificationCountdownPalette.Sample(color, color, 1)); + } +} + +public class NotificationCountdownConfigTests +{ + [Fact] + public void CountdownDefaultsToTheEdgeOutline() + { + NotificationChannelSettings settings = new(); + + Assert.Equal((int)NotificationCountdownStyle.Edge, settings.CountdownStyle); + Assert.True(settings.UsesEdgeCountdown); + Assert.Equal((int)NotificationCountdownColorMode.Gradient, settings.CountdownColorMode); + Assert.Equal(NotificationCountdownPalette.DefaultStart, settings.CountdownGradientStart); + Assert.Equal(NotificationCountdownPalette.DefaultEnd, settings.CountdownGradientEnd); + Assert.Equal(NotificationCountdownPalette.DefaultStart, settings.ResolvedCountdownStart); + Assert.Equal(NotificationCountdownPalette.DefaultEnd, settings.ResolvedCountdownEnd); + } + + [Fact] + public void SolidColorModeResolvesBothEndsToTheSingleColor() + { + NotificationChannelSettings settings = new() + { + CountdownColorMode = (int)NotificationCountdownColorMode.Solid, + CountdownSolidColor = Color.FromArgb(10, 1, 2, 3) + }; + + Assert.Equal((byte)255, settings.ResolvedCountdownStart.A); + Assert.Equal((byte)1, settings.ResolvedCountdownStart.R); + Assert.Equal(settings.ResolvedCountdownStart, settings.ResolvedCountdownEnd); + } + + [Fact] + public void GradientEndpointsAreStoredOpaque() + { + NotificationChannelSettings settings = new() + { + CountdownGradientStart = Color.FromArgb(12, 10, 20, 30), + CountdownGradientEnd = Color.FromArgb(34, 40, 50, 60) + }; + + Assert.Equal((byte)255, settings.CountdownGradientStart.A); + Assert.Equal((byte)255, settings.CountdownGradientEnd.A); + } + + [Fact] + public void CountdownStyleRejectsUnknownValues() + { + NotificationChannelSettings settings = new() + { + CountdownStyle = 9, + CountdownColorMode = 7 + }; + + Assert.Equal((int)NotificationCountdownStyle.Edge, settings.CountdownStyle); + Assert.Equal((int)NotificationCountdownColorMode.Gradient, settings.CountdownColorMode); + } + + [Fact] + public void DeserializationMigratesLegacyColorStopListToItsEndpoints() + { + const string json = """ + { + "countdown_style": 9, + "countdown_color_mode": 7, + "countdown_gradient_colors": ["#112233", "#445566", "#778899"] + } + """; + + NotificationChannelSettings? settings = JsonSerializer.Deserialize( + json, + ConfigServiceBase.JsonOptions); + + Assert.NotNull(settings); + Assert.Equal((int)NotificationCountdownStyle.Edge, settings.CountdownStyle); + Assert.Equal(Color.Parse("#112233"), settings.CountdownGradientStart); + Assert.Equal(Color.Parse("#778899"), settings.CountdownGradientEnd); + } + + [Fact] + public void CountdownSettingsRoundTripThroughJson() + { + NotificationChannelSettings settings = new() + { + CountdownStyle = (int)NotificationCountdownStyle.Text, + CountdownColorMode = (int)NotificationCountdownColorMode.Solid, + CountdownSolidColor = Colors.Orange, + CountdownGradientStart = Color.FromArgb(255, 1, 2, 3), + CountdownGradientEnd = Color.FromArgb(255, 4, 5, 6) + }; + + var json = JsonSerializer.Serialize(settings, ConfigServiceBase.JsonOptions); + NotificationChannelSettings? restored = JsonSerializer.Deserialize( + json, + ConfigServiceBase.JsonOptions); + + Assert.Contains("\"countdown_style\"", json, StringComparison.Ordinal); + Assert.Contains("\"countdown_gradient_start\"", json, StringComparison.Ordinal); + Assert.DoesNotContain("countdown_gradient_colors", json, StringComparison.Ordinal); + Assert.NotNull(restored); + Assert.Equal((int)NotificationCountdownStyle.Text, restored.CountdownStyle); + Assert.False(restored.UsesEdgeCountdown); + Assert.Equal((int)NotificationCountdownColorMode.Solid, restored.CountdownColorMode); + Assert.Equal(NotificationCountdownPalette.ToOpaque(Colors.Orange), restored.CountdownSolidColor); + Assert.Equal(settings.CountdownGradientStart, restored.CountdownGradientStart); + Assert.Equal(settings.CountdownGradientEnd, restored.CountdownGradientEnd); + } +} \ No newline at end of file diff --git a/SecRandom.Core.Tests/NotificationWindowPositionTests.cs b/SecRandom.Core.Tests/NotificationWindowPositionTests.cs new file mode 100644 index 000000000..29242901e --- /dev/null +++ b/SecRandom.Core.Tests/NotificationWindowPositionTests.cs @@ -0,0 +1,163 @@ +using System.Text.Json; +using System.Xml.Linq; +using SecRandom.Core.Abstraction; +using SecRandom.Core.Models.SubConfigs; + +namespace SecRandom.Core.Tests; + +public class NotificationWindowPositionTests +{ + /// + /// 0–4 是旧版只有五档时的取值,升级后必须落在同一个地方: + /// 中心 / 顶部居中 / 底部居中 / 左侧居中 / 右侧居中。 + /// + [Fact] + public void LegacyValuesKeepTheirAnchor() + { + Assert.Equal( + (NotificationWindowHorizontalAnchor.Center, NotificationWindowVerticalAnchor.Center), + NotificationWindowAnchorLayout.Resolve(0)); + Assert.Equal( + (NotificationWindowHorizontalAnchor.Center, NotificationWindowVerticalAnchor.Top), + NotificationWindowAnchorLayout.Resolve(1)); + Assert.Equal( + (NotificationWindowHorizontalAnchor.Center, NotificationWindowVerticalAnchor.Bottom), + NotificationWindowAnchorLayout.Resolve(2)); + Assert.Equal( + (NotificationWindowHorizontalAnchor.Left, NotificationWindowVerticalAnchor.Center), + NotificationWindowAnchorLayout.Resolve(3)); + Assert.Equal( + (NotificationWindowHorizontalAnchor.Right, NotificationWindowVerticalAnchor.Center), + NotificationWindowAnchorLayout.Resolve(4)); + } + + [Fact] + public void AppendedCornersResolveToTheirCorner() + { + Assert.Equal( + (NotificationWindowHorizontalAnchor.Left, NotificationWindowVerticalAnchor.Top), + NotificationWindowAnchorLayout.Resolve(5)); + Assert.Equal( + (NotificationWindowHorizontalAnchor.Right, NotificationWindowVerticalAnchor.Top), + NotificationWindowAnchorLayout.Resolve(6)); + Assert.Equal( + (NotificationWindowHorizontalAnchor.Left, NotificationWindowVerticalAnchor.Bottom), + NotificationWindowAnchorLayout.Resolve(7)); + Assert.Equal( + (NotificationWindowHorizontalAnchor.Right, NotificationWindowVerticalAnchor.Bottom), + NotificationWindowAnchorLayout.Resolve(8)); + } + + [Fact] + public void GridOrderCoversEveryValueExactlyOnce() + { + Assert.Equal(NotificationWindowAnchorLayout.CellCount, NotificationWindowAnchorLayout.GridOrder.Count); + Assert.Equal( + Enumerable.Range(0, NotificationWindowAnchorLayout.CellCount).OrderBy(value => value), + NotificationWindowAnchorLayout.GridOrder.Select(position => (int)position).OrderBy(value => value)); + + for (var index = 0; index < NotificationWindowAnchorLayout.GridOrder.Count; index++) + { + var value = (int)NotificationWindowAnchorLayout.GridOrder[index]; + Assert.Equal(index, NotificationWindowAnchorLayout.ToCellIndex(value)); + } + } + + [Theory] + [InlineData(-1)] + [InlineData(9)] + [InlineData(int.MaxValue)] + public void UndefinedValuesFallBackToCenter(int value) + { + Assert.False(NotificationWindowAnchorLayout.IsDefined(value)); + Assert.Equal(NotificationWindowPosition.Center, NotificationWindowAnchorLayout.Normalize(value)); + Assert.Equal( + (NotificationWindowHorizontalAnchor.Center, NotificationWindowVerticalAnchor.Center), + NotificationWindowAnchorLayout.Resolve(value)); + Assert.Equal( + NotificationWindowAnchorLayout.ToCellIndex((int)NotificationWindowPosition.Center), + NotificationWindowAnchorLayout.ToCellIndex(value)); + } + + [Fact] + public void ChannelSettingsClampUndefinedPosition() + { + NotificationChannelSettings defaults = new(); + Assert.Equal((int)NotificationWindowPosition.Center, defaults.WindowPosition); + + NotificationChannelSettings corners = new() + { + WindowPosition = (int)NotificationWindowPosition.BottomRight + }; + Assert.Equal((int)NotificationWindowPosition.BottomRight, corners.WindowPosition); + + NotificationChannelSettings outOfRange = new() { WindowPosition = 42 }; + Assert.Equal((int)NotificationWindowPosition.Center, outOfRange.WindowPosition); + + // 旧配置缺这个键时反序列化同样得到中心。 + NotificationChannelSettings? missing = JsonSerializer.Deserialize( + "{}", + ConfigServiceBase.JsonOptions); + Assert.NotNull(missing); + Assert.Equal((int)NotificationWindowPosition.Center, missing.WindowPosition); + } + + [Fact] + public void ChannelSettingsPersistPositionUnderTheLegacyJsonKey() + { + NotificationChannelSettings settings = new() + { + WindowPosition = (int)NotificationWindowPosition.TopLeft + }; + + string json = JsonSerializer.Serialize(settings, ConfigServiceBase.JsonOptions); + Assert.Contains("\"window_position\": 5", json, StringComparison.Ordinal); + + NotificationChannelSettings? restored = JsonSerializer.Deserialize( + """{ "window_position": 7 }""", + ConfigServiceBase.JsonOptions); + + Assert.NotNull(restored); + Assert.Equal((int)NotificationWindowPosition.BottomLeft, restored.WindowPosition); + } + + /// + /// 圆点选择器的九格提示直接取自这些资源键;缺一个就会有格子没有名字(悬停提示与无障碍名称同时丢失)。 + /// + [Theory] + [InlineData("Resources.resx")] + [InlineData("Resources.en-US.resx")] + [InlineData("Resources.ja-JP.resx")] + public void NotificationResourcesLocalizeEveryAnchor(string fileName) + { + string repositoryRoot = Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "../../../..")); + XDocument resource = XDocument.Load(Path.Combine( + repositoryRoot, + "SecRandom/Langs/SettingsPages/Notification", + fileName)); + string[] expectedKeys = + [ + "O_WindowPosition_Center", + "O_WindowPosition_Top", + "O_WindowPosition_Bottom", + "O_WindowPosition_Left", + "O_WindowPosition_Right", + "O_WindowPosition_TopLeft", + "O_WindowPosition_TopRight", + "O_WindowPosition_BottomLeft", + "O_WindowPosition_BottomRight" + ]; + + var localized = resource.Root? + .Elements("data") + .Where(element => expectedKeys.Contains((string?)element.Attribute("name"))) + .ToDictionary( + element => (string)element.Attribute("name")!, + element => element.Element("value")?.Value) + .Where(pair => !string.IsNullOrWhiteSpace(pair.Value)) + .Select(pair => pair.Key) + .ToHashSet() ?? []; + + Assert.Equal(expectedKeys.OrderBy(key => key), localized.OrderBy(key => key)); + } +} \ No newline at end of file diff --git a/SecRandom.Core.Tests/OrchestrationOrderingTests.cs b/SecRandom.Core.Tests/OrchestrationOrderingTests.cs new file mode 100644 index 000000000..54d549d24 --- /dev/null +++ b/SecRandom.Core.Tests/OrchestrationOrderingTests.cs @@ -0,0 +1,312 @@ +using SecRandom.Core.Enums.Configs; +using SecRandom.Core.Interfaces; +using SecRandom.Core.Models.Orchestration; +using SecRandom.Core.Services.Orchestration; +using Xunit; + +namespace SecRandom.Core.Tests; + +/// +/// 编排抽取的顺序解析:一轮是一条队列,五份名单是一轮里的五种规则,而不是五份互相覆盖的绝对位置表。 +/// +public class OrchestrationOrderingTests +{ + private static readonly DateTime Base = new(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc); + + private sealed class FixedRandomSource(double value) : IRandomSource + { + public int NextInt32(int maxExclusive) => maxExclusive <= 0 ? 0 : Math.Min(maxExclusive - 1, (int)(value * maxExclusive)); + + public double NextDouble() => value; + } + + private static Guid Id(int seed) => new(seed, 0, 0, new byte[8]); + + private static OrchestrationCandidate Candidate(int seed, double weight = 1d, int count = 0) => + new(Id(seed), weight, count, Base.AddDays(-count), false); + + private static OrchestrationRound Round(int index = 1) => new() { Index = index }; + + private static OrchestrationRules Rules() => new(); + + private static IReadOnlyList Resolve( + IReadOnlyList candidates, + OrchestrationRound round, + OrchestrationRules? rules = null, + IReadOnlySet? drawn = null) => + OrchestrationOrdering.Resolve( + candidates, round, drawn ?? new HashSet(), new FixedRandomSource(0.5), rules ?? Rules()); + + [Fact] + public void QueueIsFollowedAndTheDrawnMemberLeavesSoTheNextOneMovesUp() + { + var candidates = new[] { Candidate(1), Candidate(2), Candidate(3) }; + var round = Round(); + round.Order = [Id(1), Id(2), Id(3)]; + + var order = Resolve(candidates, round); + Assert.Equal([Id(1), Id(2), Id(3)], order); + + // 抽掉第一个人之后重新解析:后面的人前移,而不是重新在"剩余三个人"里坐第 3 个位置。 + var afterFirst = Resolve(candidates, round, drawn: new HashSet { Id(1) }); + Assert.Equal([Id(2), Id(3)], afterFirst); + + var afterSecond = Resolve(candidates, round, drawn: new HashSet { Id(1), Id(2) }); + Assert.Equal([Id(3)], afterSecond); + } + + [Fact] + public void QueueSkipsMembersThatLeftTheRound() + { + var round = Round(); + round.Order = [Id(1), Id(2), Id(3), Id(4)]; + round.Skipped.Add(Id(2)); + + var order = Resolve([Candidate(1), Candidate(2), Candidate(3), Candidate(4)], round); + + Assert.Equal([Id(1), Id(3), Id(4)], order); + } + + [Fact] + public void MembersOutsideTheQueueComeAfterItByWeight() + { + var round = Round(); + round.Order = [Id(3)]; + + var order = Resolve([Candidate(1), Candidate(2), Candidate(3)], round); + + Assert.Equal(3, order.Count); + Assert.Equal(Id(3), order[0]); + Assert.Equal([Id(1), Id(2)], order.Skip(1).OrderBy(id => id)); + } + + [Fact] + public void GuaranteedMembersLeadTheRound() + { + var round = Round(); + round.Guaranteed.Add(Id(3)); + var rules = Rules(); + rules.SetEnabled(OrchestrationRuleKind.Guarantee, true); + + var order = OrchestrationOrdering.Resolve( + [Candidate(1), Candidate(2), Candidate(3)], round, new HashSet(), new FixedRandomSource(0.5), + rules); + + Assert.Equal(Id(3), order[0]); + Assert.Equal(3, order.Count); + Assert.Equal(3, order.Distinct().Count()); + } + + [Fact] + public void GuaranteedGroupKeepsItsWeightOrder() + { + var round = Round(); + round.Guaranteed = [Id(1), Id(2)]; + round.Weights[Id(1)] = 5d; + var rules = Rules(); + rules.SetEnabled(OrchestrationRuleKind.Guarantee, true); + + var order = Resolve([Candidate(1), Candidate(2), Candidate(3)], round, rules); + + // 必中名单内部仍然按权重排序:权重大的先出场,权重相同才看加入次序。 + Assert.Equal([Id(1), Id(2)], order.Take(2)); + } + + [Fact] + public void GuaranteedWinsWhenAHandEditedFileCarriesBothFrontLists() + { + var round = Round(); + round.Order = [Id(2)]; + round.Guaranteed.Add(Id(3)); + var rules = Rules(); + rules.SetEnabled(OrchestrationRuleKind.Guarantee, true); + + var order = Resolve([Candidate(1), Candidate(2), Candidate(3)], round, rules); + + Assert.Equal(Id(3), order[0]); + Assert.Equal(3, order.Count); + Assert.Equal(3, order.Distinct().Count()); + } + + [Fact] + public void ExcludedSkippedAndAlreadyDrawnMembersLeaveTheRound() + { + var round = Round(); + round.Skipped.Add(Id(2)); + var excluded = new OrchestrationCandidate(Id(3), 1d, 0, Base, true); + + var order = Resolve( + [Candidate(1), Candidate(2), excluded, Candidate(4)], round, drawn: new HashSet { Id(4) }); + + Assert.Equal([Id(1)], order); + } + + [Fact] + public void ExcludedMembersComeBackWhenTheExcludeListIsSwitchedOff() + { + var excluded = new OrchestrationCandidate(Id(3), 1d, 0, Base, true); + var rules = Rules(); + rules.SetEnabled(OrchestrationRuleKind.Exclude, false); + + var order = Resolve([Candidate(1), excluded], Round(), rules); + + Assert.Equal([Id(1), Id(3)], order.OrderBy(id => id)); + } + + [Fact] + public void DeferredMembersComeBackWhenTheDeferListIsSwitchedOff() + { + var round = Round(); + round.Order = [Id(2), Id(1)]; + round.Skipped.Add(Id(2)); + var rules = Rules(); + rules.SetEnabled(OrchestrationRuleKind.Defer, false); + + var order = Resolve([Candidate(1), Candidate(2)], round, rules); + + Assert.Equal([Id(2), Id(1)], order); + } + + [Fact] + public void ZeroWeightMembersAreDeferredInsteadOfDropped() + { + var order = Resolve( + [Candidate(1, weight: 0d, count: 3), Candidate(2, weight: 0d, count: 1), Candidate(3, weight: 1d)], + Round()); + + Assert.Equal(3, order.Count); + Assert.Equal(Id(3), order[0]); + // The deferred tail is ordered by draw count, most-drawn first: the ceiling protects nobody by omission. + Assert.Equal(Id(1), order[1]); + Assert.Equal(Id(2), order[2]); + } + + [Fact] + public void ManualWeightIsAppliedAsAMultiplier() + { + var round = Round(); + round.Weights[Id(1)] = 0d; + + var order = Resolve([Candidate(1, weight: 5d), Candidate(2, weight: 1d)], round); + + // Weight 0 does not ban the member, it moves it behind the weighted fill. + Assert.Equal(Id(2), order[0]); + Assert.Equal(Id(1), order[1]); + } + + [Fact] + public void ManualWeightIsIgnoredWhenTheWeightListIsSwitchedOff() + { + var round = Round(); + round.Weights[Id(1)] = 0d; + var rules = Rules(); + rules.SetEnabled(OrchestrationRuleKind.Weight, false); + + var order = Resolve([Candidate(1, weight: 5d), Candidate(2, weight: 1d)], round, rules); + + // 关掉权重名单后手动值留在数据里但不参与:Id(1) 的采样权重更高,先出场。 + Assert.Equal(Id(1), order[0]); + Assert.Equal(Id(2), order[1]); + } + + [Fact] + public void WeightedFillUsesEveryRemainingCandidateExactlyOnce() + { + var candidates = Enumerable.Range(1, 20).Select(seed => Candidate(seed, weight: seed)).ToList(); + + var order = Resolve(candidates, Round()); + + Assert.Equal(candidates.Count, order.Count); + Assert.Equal(candidates.Select(candidate => candidate.RecordId).OrderBy(id => id), + order.OrderBy(id => id)); + } + + [Fact] + public void RoundCountIsClampedAndRulesAreFilledInWhenLoadingAnOldProfile() + { + var profile = new OrchestrationProfile + { + Id = "abc", + RoundCount = 99, + Members = [new OrchestrationMember { RecordId = Id(1), Number = "1", Name = "A" }], + Rounds = + [ + new OrchestrationRound { Index = 3, Order = [Id(1)], LegacyPins = [new OrchestrationPin { RecordId = Id(1), Position = 1 }] }, + new OrchestrationRound { Index = 42 } + ] + }; + profile.Rules = null!; + + OrchestrationStore.Normalize(profile); + + Assert.Equal(OrchestrationProfile.CurrentFormatVersion, profile.FormatVersion); + Assert.Equal(10, profile.EffectiveRoundCount); + Assert.Equal([3], profile.Rounds.Select(round => round.Index)); + Assert.NotNull(profile.Rules); + Assert.True(profile.Rules.Order); + Assert.False(profile.Rules.Guarantee); + } + + [Fact] + public void LegacyPinsBecomeTheRoundQueueInPinOrder() + { + var profile = new OrchestrationProfile + { + Id = "abc", + RoundCount = 2, + Members = + [ + new OrchestrationMember { RecordId = Id(1), Number = "1", Name = "A" }, + new OrchestrationMember { RecordId = Id(2), Number = "2", Name = "B" }, + new OrchestrationMember { RecordId = Id(3), Number = "3", Name = "C" } + ], + Rounds = + [ + new OrchestrationRound + { + Index = 1, + Order = [Id(1)], + LegacyPins = [new OrchestrationPin { RecordId = Id(3), Position = 1 }, new OrchestrationPin { RecordId = Id(2), Position = 2 }] + } + ] + }; + + OrchestrationStore.Normalize(profile); + + var round = profile.GetRound(1); + // 旧 pin 的绝对槽位不保留,只保留它表达的相对次序:3 → 2,再接原来的副本 1。 + Assert.Equal([Id(3), Id(2), Id(1)], round.Order); + Assert.Null(round.LegacyPins); + } + + [Fact] + public void RoundListsOnlyKeepMembersThatStillExist() + { + var profile = new OrchestrationProfile + { + Id = "abc", + Members = [new OrchestrationMember { RecordId = Id(1), Number = "1", Name = "A" }], + Rounds = + [ + new OrchestrationRound + { + Index = 1, + Order = [Id(1), Id(9)], + Skipped = [Id(9)], + Guaranteed = [Id(9)], + Weights = new Dictionary { [Id(9)] = 50d } + } + ] + }; + + OrchestrationStore.Normalize(profile); + + var round = profile.GetRound(1); + Assert.Equal([Id(1)], round.Order); + Assert.Empty(round.Skipped); + Assert.Empty(round.Guaranteed); + Assert.Empty(round.Weights); + Assert.Equal(OrchestrationTarget.RollCall, profile.Target); + Assert.True(profile.Rules.Exclude); + } +} \ No newline at end of file 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/ProfileCatalogManagerTests.cs b/SecRandom.Core.Tests/ProfileCatalogManagerTests.cs index 20551bd6f..4c7ec69de 100644 --- a/SecRandom.Core.Tests/ProfileCatalogManagerTests.cs +++ b/SecRandom.Core.Tests/ProfileCatalogManagerTests.cs @@ -342,6 +342,105 @@ public void DeletePrizeList_RemovesListAndSyncsActiveProfile() Assert.Equal(fallbackName, profile.PrizeListConfig!.Name); } + [Fact] + public void DeleteLastStudentList_LeavesNoActiveProfile() + { + using var provider = CreateProvider(); + var profile = provider.GetRequiredService(); + var manager = provider.GetRequiredService(); + var onlyName = profile.StudentListConfig!.Name; + Assert.Equal([onlyName], manager.GetStudentListNames()); + + Assert.True(manager.DeleteStudentList(onlyName, deleteHistory: true)); + + // 名单可以全部删掉:删完不能再有活动档案,否则内存里会留着一份已删除的名单。 + Assert.Empty(manager.GetStudentListNames()); + Assert.Null(profile.StudentListConfig); + Assert.Null(profile.CurrentStudentList); + Assert.Null(profile.StudentHistoryConfig); + Assert.Null(profile.CurrentStudentHistory); + Assert.Empty(profile.StudentHistoryConfig?.Data.HistoryGroups ?? []); + Assert.False(File.Exists(Utils.GetFilePath("list", "roll_call_list", $"{onlyName}.json"))); + } + + [Fact] + public void DeleteLastPrizeList_LeavesNoActiveProfile() + { + using var provider = CreateProvider(); + var profile = provider.GetRequiredService(); + var manager = provider.GetRequiredService(); + var onlyName = profile.PrizeListConfig!.Name; + + Assert.True(manager.DeletePrizeList(onlyName, deleteHistory: true)); + + Assert.Empty(manager.GetPrizeListNames()); + Assert.Null(profile.PrizeListConfig); + Assert.Null(profile.CurrentPrizeList); + Assert.Null(profile.PrizeHistoryConfig); + Assert.Null(profile.CurrentPrizeHistory); + Assert.False(File.Exists(Utils.GetFilePath("list", "lottery_list", $"{onlyName}.json"))); + } + + [Fact] + public void EmptyListState_SurvivesRestartOnceTheGuideIsCompleted() + { + using (var provider = CreateProvider()) + { + var config = provider.GetRequiredService(); + var manager = provider.GetRequiredService(); + var profile = provider.GetRequiredService(); + + // 引导完成后空目录就是「没有名单」;只有首次运行才会补一份 default。 + config.Data.General.Basic.GuideCompleted = true; + config.Save(); + + Assert.True(manager.DeleteStudentList(profile.StudentListConfig!.Name, deleteHistory: true)); + Assert.True(manager.DeletePrizeList(profile.PrizeListConfig!.Name, deleteHistory: true)); + } + + using (var restarted = CreateProvider()) + { + var config = restarted.GetRequiredService(); + var profile = restarted.GetRequiredService(); + Assert.True(config.Data.General.Basic.GuideCompleted); + // 重启不补建:删掉最后一份名单之后,零名单状态必须是真的零名单。 + Assert.Null(profile.StudentListConfig); + Assert.Null(profile.PrizeListConfig); + Assert.False(File.Exists(Utils.GetFilePath("list", "roll_call_list", "default.json"))); + Assert.False(File.Exists(Utils.GetFilePath("list", "lottery_list", "default.json"))); + } + } + + [Fact] + public void FirstRun_StillSeedsOneDefaultListPerChannel() + { + using var provider = CreateProvider(); + var config = provider.GetRequiredService(); + var profile = provider.GetRequiredService(); + + Assert.False(config.Data.General.Basic.GuideCompleted); + Assert.Equal("default", profile.StudentListConfig!.Name); + Assert.Equal("default", profile.PrizeListConfig!.Name); + } + + [Fact] + public void SetDefaultList_AcceptsEmptyToClearADeletedList() + { + using var provider = CreateProvider(); + var config = provider.GetRequiredService(); + var manager = provider.GetRequiredService(); + + manager.SetDefaultStudentList("class-default"); + manager.SetDefaultPrizePool("pool-default"); + Assert.Equal("class-default", config.Data.RollCallSettings.DefaultClass); + Assert.Equal("pool-default", config.Data.LotterySettings.DefaultPool); + + manager.SetDefaultStudentList(string.Empty); + manager.SetDefaultPrizePool(string.Empty); + Assert.Equal(string.Empty, config.Data.RollCallSettings.DefaultClass); + Assert.Equal(string.Empty, config.Data.LotterySettings.DefaultPool); + } + [Fact] public void RenameStudentList_MovesDataHistoryTemporaryRecordsAndUpdatesActiveProfile() { diff --git a/SecRandom.Core.Tests/ProfileSequenceNumberingTests.cs b/SecRandom.Core.Tests/ProfileSequenceNumberingTests.cs index defe7550f..6cdcf467e 100644 --- a/SecRandom.Core.Tests/ProfileSequenceNumberingTests.cs +++ b/SecRandom.Core.Tests/ProfileSequenceNumberingTests.cs @@ -134,4 +134,94 @@ public void Analyze_KeepsShiftedNumbersUnique() Assert.DoesNotContain("7", shifted); Assert.Contains("7", ids); } + + [Fact] + public void AnalyzeRemoval_ShiftsLaterNumbersForward() + { + var removal = ProfileSequenceNumbering.AnalyzeRemoval(["1", "2", "3", "4"], 1); + + Assert.True(removal.CanShift); + Assert.Equal(1, removal.RemovedIndex); + Assert.Equal("2", removal.RemovedId); + Assert.Equal(2, removal.RemovedNumber); + Assert.Equal([2, 3], removal.ShiftEntries.Select(entry => entry.Index)); + Assert.Equal([3L, 4L], removal.ShiftEntries.Select(entry => entry.OldNumber)); + Assert.Equal([2L, 3L], removal.ShiftEntries.Select(entry => entry.NewNumber)); + } + + [Fact] + public void AnalyzeRemoval_DoesNotOfferShift_WhenRemovedNumberIsTheLastNumber() + { + var removal = ProfileSequenceNumbering.AnalyzeRemoval(["1", "2", "3"], 2); + + Assert.False(removal.CanShift); + Assert.Equal(3, removal.RemovedNumber); + Assert.Empty(removal.ShiftEntries); + } + + [Fact] + public void AnalyzeRemoval_DoesNotOfferShift_WhenRemovedIdIsNotNumeric() + { + var removal = ProfileSequenceNumbering.AnalyzeRemoval(["A1", "2", "3"], 0); + + Assert.False(removal.CanShift); + Assert.Null(removal.RemovedNumber); + Assert.Empty(removal.ShiftEntries); + } + + [Fact] + public void AnalyzeRemoval_DoesNotOfferShift_WhenAnotherMemberUsesTheSameNumber() + { + var removal = ProfileSequenceNumbering.AnalyzeRemoval(["1", "2", "2", "3"], 1); + + Assert.False(removal.CanShift); + Assert.Equal(2, removal.RemovedNumber); + Assert.Empty(removal.ShiftEntries); + } + + [Fact] + public void AnalyzeRemoval_DoesNotOfferShift_WhenIndexIsInvalid() + { + Assert.False(ProfileSequenceNumbering.AnalyzeRemoval(["1", "2"], -1).CanShift); + Assert.False(ProfileSequenceNumbering.AnalyzeRemoval(["1", "2"], 2).CanShift); + Assert.False(ProfileSequenceNumbering.AnalyzeRemoval(null, 0).CanShift); + } + + [Fact] + public void AnalyzeRemoval_LeavesNonNumericIdsUntouched() + { + var removal = ProfileSequenceNumbering.AnalyzeRemoval(["A1", "3", "初一(3)班-07", "5"], 1); + + Assert.True(removal.CanShift); + Assert.Equal([3], removal.ShiftEntries.Select(entry => entry.Index)); + Assert.Equal(5L, removal.ShiftEntries[0].OldNumber); + Assert.Equal(4L, removal.ShiftEntries[0].NewNumber); + } + + [Fact] + public void AnalyzeRemoval_KeepsShiftedNumbersUnique() + { + string[] ids = ["3", "7", "8", "12", "A"]; + var removal = ProfileSequenceNumbering.AnalyzeRemoval(ids, 1); + + var shifted = ids.ToArray(); + foreach (var entry in removal.ShiftEntries) + shifted[entry.Index] = entry.NewNumber.ToString(); + + Assert.True(removal.CanShift); + Assert.Equal([7L, 11L], removal.ShiftEntries.Select(entry => entry.NewNumber)); + Assert.Equal(shifted.Length - 1, shifted.Where((_, index) => index != 1).Distinct(StringComparer.Ordinal).Count()); + } + + [Fact] + public void AnalyzeRemoval_HandlesLeadingZerosAndLongNumbers() + { + var leadingZeros = ProfileSequenceNumbering.AnalyzeRemoval(["007", "008"], 0); + Assert.True(leadingZeros.CanShift); + Assert.Equal(7L, leadingZeros.ShiftEntries[0].NewNumber); + + var longNumbers = ProfileSequenceNumbering.AnalyzeRemoval(["20260101001", "20260101002"], 0); + Assert.True(longNumbers.CanShift); + Assert.Equal(20260101001L, longNumbers.ShiftEntries[0].NewNumber); + } } 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/QuickDrawHoldDurationTests.cs b/SecRandom.Core.Tests/QuickDrawHoldDurationTests.cs new file mode 100644 index 000000000..805a3703e --- /dev/null +++ b/SecRandom.Core.Tests/QuickDrawHoldDurationTests.cs @@ -0,0 +1,51 @@ +using SecRandom.Core.Services.FloatingWindow; + +namespace SecRandom.Core.Tests; + +public class QuickDrawHoldDurationTests +{ + [Theory] + [InlineData(500, 500)] + [InlineData(40, 40)] + [InlineData(3000, 3000)] + public void PrimaryButton_KeepsTheConfiguredDuration(int configured, int expected) + { + Assert.Equal(expected, QuickDrawLongPressGesture.ResolveHoldDuration(configured, isSecondaryButton: false)); + } + + [Theory] + [InlineData(500, 160)] + [InlineData(3000, 160)] + [InlineData(40, 40)] + public void SecondaryButton_ShortensToItsConfirmationWindow(int configured, int expected) + { + // 右键是 Windows 触控长按的替身:用户真正的按住时长已经被系统用掉, + // 所以不能再等满配置值,但也不能一按下就当长按。 + Assert.Equal(expected, QuickDrawLongPressGesture.ResolveHoldDuration(configured, isSecondaryButton: true)); + } + + [Fact] + public void BothButtons_StayInsideTheExecutableRange() + { + Assert.Equal( + QuickDrawLongPressGesture.MinHoldDurationMilliseconds, + QuickDrawLongPressGesture.ResolveHoldDuration(-10, isSecondaryButton: false)); + Assert.Equal( + QuickDrawLongPressGesture.MinHoldDurationMilliseconds, + QuickDrawLongPressGesture.ResolveHoldDuration(-10, isSecondaryButton: true)); + Assert.Equal( + QuickDrawLongPressGesture.MaxHoldDurationMilliseconds, + QuickDrawLongPressGesture.ResolveHoldDuration(int.MaxValue, isSecondaryButton: false)); + Assert.Equal( + QuickDrawLongPressGesture.SecondaryButtonHoldDurationMilliseconds, + QuickDrawLongPressGesture.ResolveHoldDuration(int.MaxValue, isSecondaryButton: true)); + } + + [Fact] + public void SecondaryWindow_IsShorterThanTheDefaultHold() + { + Assert.True( + QuickDrawLongPressGesture.SecondaryButtonHoldDurationMilliseconds + < QuickDrawLongPressGesture.DefaultHoldDurationMilliseconds); + } +} diff --git a/SecRandom.Core.Tests/QuickDrawLongPressGestureTests.cs b/SecRandom.Core.Tests/QuickDrawLongPressGestureTests.cs new file mode 100644 index 000000000..68f3c6f85 --- /dev/null +++ b/SecRandom.Core.Tests/QuickDrawLongPressGestureTests.cs @@ -0,0 +1,189 @@ +using Avalonia; +using Avalonia.Media; +using SecRandom.Core.Services.FloatingWindow; + +namespace SecRandom.Core.Tests; + +public class QuickDrawLongPressGestureTests +{ + [Fact] + public void RowCounts_MirrorWithPickerSide() + { + IReadOnlyList onLeft = QuickDrawLongPressGesture.ResolveRowCounts(pickerOnLeft: true); + IReadOnlyList onRight = QuickDrawLongPressGesture.ResolveRowCounts(pickerOnLeft: false); + + Assert.Equal(new[] { 5, 4, 3, 2, 1, 0 }, onLeft); + Assert.Equal(new[] { 0, 1, 2, 3, 4, 5 }, onRight); + Assert.Equal(QuickDrawLongPressGesture.OptionCount, onLeft.Count); + } + + [Fact] + public void PickerSitsOppositeTheWindowSide() + { + Assert.True(QuickDrawLongPressGesture.ResolvePickerOnLeft(windowOnLeft: false)); + Assert.False(QuickDrawLongPressGesture.ResolvePickerOnLeft(windowOnLeft: true)); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void ResolveCount_ClampsToColumnEnds(bool pickerOnLeft) + { + IReadOnlyList rows = QuickDrawLongPressGesture.ResolveRowCounts(pickerOnLeft); + const double top = 100; + const double height = 300; + + Assert.Equal(rows[0], QuickDrawLongPressGesture.ResolveCount(top - 500, top, height, rows)); + Assert.Equal(rows[0], QuickDrawLongPressGesture.ResolveCount(top, top, height, rows)); + Assert.Equal(rows[^1], QuickDrawLongPressGesture.ResolveCount(top + height + 500, top, height, rows)); + Assert.Equal(rows[^1], QuickDrawLongPressGesture.ResolveCount(top + height - 1, top, height, rows)); + + // 行心一定落在自己那一行:逐行取中心验证,行序两端与"退出"都测得准。 + for (int index = 0; index < rows.Count; index++) + { + double center = top + (index * (height / rows.Count)) + (height / rows.Count / 2); + Assert.Equal(rows[index], QuickDrawLongPressGesture.ResolveCount(center, top, height, rows)); + } + } + + [Fact] + public void DefaultCount_LandsOnTheRowUnderTheFinger() + { + IReadOnlyList rows = QuickDrawLongPressGesture.ResolveRowCounts(pickerOnLeft: true); + int index = QuickDrawLongPressGesture.ResolveRowIndex(rows, QuickDrawLongPressGesture.DefaultCount); + + Assert.Equal(4, index); + Assert.Equal(QuickDrawLongPressGesture.DefaultCount, rows[index]); + Assert.Equal(QuickDrawLongPressGesture.DefaultCount, + QuickDrawLongPressGesture.ResolveCount(100 + (index * 50) + 25, 100, 300, rows)); + } + + [Fact] + public void ResolveRowIndex_FallsBackToDefaultRowThenFirst() + { + IReadOnlyList rows = QuickDrawLongPressGesture.ResolveRowCounts(pickerOnLeft: true); + + Assert.Equal(0, QuickDrawLongPressGesture.ResolveRowIndex(rows, 5)); + Assert.Equal(4, QuickDrawLongPressGesture.ResolveRowIndex(rows, 99)); + Assert.Equal(0, QuickDrawLongPressGesture.ResolveRowIndex([], 99)); + } + + [Fact] + public void ProgressAndRingColor_StayInsideTheirRange() + { + Assert.Equal(0, QuickDrawLongPressGesture.ResolveProgress(-10, 500)); + Assert.Equal(0.5, QuickDrawLongPressGesture.ResolveProgress(250, 500), 3); + Assert.Equal(1, QuickDrawLongPressGesture.ResolveProgress(900, 500)); + + Color start = QuickDrawLongPressGesture.ResolveRingColor(0); + Color end = QuickDrawLongPressGesture.ResolveRingColor(1); + + Assert.True(start.B > start.G); + Assert.True(end.G > end.B); + Assert.Equal(255, start.A); + Assert.Equal(QuickDrawLongPressGesture.ResolveRingColor(1), QuickDrawLongPressGesture.ResolveRingColor(5)); + } + + [Fact] + public void HoldDuration_IsClamped() + { + Assert.Equal(QuickDrawLongPressGesture.MinHoldDurationMilliseconds, + QuickDrawLongPressGesture.NormalizeHoldDuration(0)); + Assert.Equal(QuickDrawLongPressGesture.MaxHoldDurationMilliseconds, + QuickDrawLongPressGesture.NormalizeHoldDuration(60_000)); + Assert.Equal(500, QuickDrawLongPressGesture.NormalizeHoldDuration(500)); + } + + [Fact] + public void DragBeyondTheThreshold_CancelsTheHold() + { + Point start = new(100, 100); + + Assert.False(QuickDrawLongPressGesture.ShouldCancelForDrag(start, new Point(104, 104))); + Assert.True(QuickDrawLongPressGesture.ShouldCancelForDrag( + start, + new Point(100 + QuickDrawLongPressGesture.DragCancelDistance + 1, 100))); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void DragTolerance_FollowsThePointerKind(bool isTouchOrPen) + { + Point start = new(100, 100); + + // 触控容差必须比鼠标宽松,否则手指按住时的自然漂移会被误判成拖窗。 + Assert.True(QuickDrawLongPressGesture.TouchDragCancelDistance > + QuickDrawLongPressGesture.DragCancelDistance); + Assert.Equal( + isTouchOrPen + ? QuickDrawLongPressGesture.TouchDragCancelDistance + : QuickDrawLongPressGesture.DragCancelDistance, + QuickDrawLongPressGesture.ResolveDragCancelDistance(isTouchOrPen)); + + // 同一段位移:鼠标已经算拖动,触控还在点按容差内;超过触控容差才取消长按。 + double mouseTolerance = QuickDrawLongPressGesture.ResolveDragCancelDistance(false); + double touchTolerance = QuickDrawLongPressGesture.ResolveDragCancelDistance(true); + double between = (mouseTolerance + touchTolerance) / 2; + + Assert.True(QuickDrawLongPressGesture.ShouldCancelForDrag( + start, new Point(start.X + between, start.Y), isTouchOrPen: false)); + Assert.False(QuickDrawLongPressGesture.ShouldCancelForDrag( + start, new Point(start.X + between, start.Y), isTouchOrPen: true)); + Assert.True(QuickDrawLongPressGesture.ShouldCancelForDrag( + start, new Point(start.X + touchTolerance + 1, start.Y), isTouchOrPen: true)); + Assert.False(QuickDrawLongPressGesture.ShouldCancelForDrag( + start, new Point(start.X, start.Y + 1), isTouchOrPen)); + } + + [Fact] + public void SelectionActivation_LeavesMoreRoomForTouch() + { + Assert.True(QuickDrawLongPressGesture.TouchSelectionActivationDistance > + QuickDrawLongPressGesture.SelectionActivationDistance); + Assert.Equal(QuickDrawLongPressGesture.SelectionActivationDistance, + QuickDrawLongPressGesture.ResolveSelectionActivationDistance(false)); + Assert.Equal(QuickDrawLongPressGesture.TouchSelectionActivationDistance, + QuickDrawLongPressGesture.ResolveSelectionActivationDistance(true)); + } + + [Fact] + public void Layout_KeepsPickerAndOrbInsideThePanel() + { + QuickPickLayout layout = QuickDrawLongPressGesture.ResolveLayout( + orbSize: 56, + pickerWidth: 96, + rowCount: QuickDrawLongPressGesture.OptionCount, + rowHeight: 52, + pickerOnLeft: true); + + Assert.True(layout.WindowSize.Width > 0); + Assert.True(layout.WindowSize.Height > 0); + Assert.True(layout.PickerRect.Right <= layout.WindowSize.Width); + Assert.True(layout.PickerRect.Bottom <= layout.WindowSize.Height); + Assert.True(layout.PickerOnLeft); + + QuickPickLayout mirrored = QuickDrawLongPressGesture.ResolveLayout( + orbSize: 56, + pickerWidth: 96, + rowCount: QuickDrawLongPressGesture.OptionCount, + rowHeight: 52, + pickerOnLeft: false); + + Assert.Equal(layout.WindowSize, mirrored.WindowSize); + Assert.True(mirrored.PickerRect.X > layout.PickerRect.X); + } + + [Fact] + public void OrbCenter_StaysInsideThePanelWhileFollowingThePointer() + { + Size window = new(200, 320); + Point center = QuickDrawLongPressGesture.ResolveOrbCenter(new Point(-500, 10_000), window, 56); + + Assert.InRange(center.X, 28, window.Width - 28); + Assert.InRange(center.Y, 28, window.Height - 28); + + Point middle = QuickDrawLongPressGesture.ResolveOrbCenter(new Point(100, 160), window, 56); + Assert.Equal(new Point(100, 160), middle); + } +} \ No newline at end of file diff --git a/SecRandom.Core.Tests/QuickDrawNotificationForegroundTests.cs b/SecRandom.Core.Tests/QuickDrawNotificationForegroundTests.cs new file mode 100644 index 000000000..59a361cf5 --- /dev/null +++ b/SecRandom.Core.Tests/QuickDrawNotificationForegroundTests.cs @@ -0,0 +1,144 @@ +using System.Reflection; +using Avalonia.Media; +using Microsoft.Extensions.Logging.Abstractions; +using SecRandom.Core.Abstraction; +using SecRandom.Core.Enums.Configs; +using SecRandom.Core.Models; +using SecRandom.Core.Services.Config; +using SecRandom.Core.Services.Presentation; +using SecRandom.Services.Draw; +using SecRandom.Shared; +using SecRandom.Shared.Models.Profile; +using SecRandom.ViewModels.MainPages; + +namespace SecRandom.Core.Tests; + +public sealed class QuickDrawNotificationForegroundTests : IDisposable +{ + private readonly string _dataRoot = Path.Combine(Path.GetTempPath(), "SecRandom.NotificationInk", Guid.NewGuid().ToString("N")); + private readonly DrawAudioService _audio = new(null!, NullLogger.Instance); + + public QuickDrawNotificationForegroundTests() + { + GetUtilsMethod("ConfigureDataRoot").Invoke(null, [_dataRoot]); + } + + [Theory] + [InlineData(true, false)] + [InlineData(false, false)] + [InlineData(true, true)] + [InlineData(false, true)] + public void NewStudentFramesUseNotificationThemeInsteadOfAppThemeOrAccent(bool darkAppTheme, bool useAccent) + { + using var viewModel = CreateViewModel(darkAppTheme, useAccent); + var theme = AdaptiveBackdropResolver.FromAppTheme(!darkAppTheme); + viewModel.ApplyNotificationTheme(theme); + + // Both rolling frames and the final student result replace this collection through the same path. + ReplaceStudentResults(viewModel, "预览学生"); + AssertInk(viewModel, theme.Foreground); + ReplaceStudentResults(viewModel, "最终学生"); + AssertInk(viewModel, theme.Foreground); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void PreparingThemeReplacesTheInkLeftByPageCreation(bool initialDarkInk) + { + using var viewModel = CreateViewModel(darkAppTheme: initialDarkInk); + // The page initially supplies app-theme ink before desktop sampling has completed. + viewModel.ApplyNotificationInk(new SolidColorBrush(initialDarkInk ? Colors.Black : Colors.White)); + ReplaceStudentResults(viewModel, "原有学生"); + + var theme = AdaptiveBackdropResolver.FromAppTheme(initialDarkInk); + viewModel.ApplyNotificationTheme(theme); + AssertInk(viewModel, theme.Foreground); + ReplaceStudentResults(viewModel, "首次显示"); + AssertInk(viewModel, theme.Foreground); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void ExplicitCardInkSurvivesNewStudentAndStringResults(bool darkInk) + { + using var viewModel = CreateViewModel(darkAppTheme: darkInk); + var ink = darkInk ? Colors.Black : Colors.White; + viewModel.ApplyNotificationInk(new SolidColorBrush(ink)); + + ReplaceStudentResults(viewModel, "学生"); + AssertInk(viewModel, ink); + viewModel.ShowNotificationPreview(["预览"], preserveQuickDrawResult: false); + AssertInk(viewModel, ink); + viewModel.ShowNotificationResult(["结果"], 5, animate: false, preserveQuickDrawResult: false); + AssertInk(viewModel, ink); + } + + [Fact] + public void ReusedResultsRecolorAndClearingNotificationRestoresAccent() + { + using var viewModel = CreateViewModel(darkAppTheme: true); + ReplaceStudentResults(viewModel, "保留学生"); + AssertInk(viewModel, Colors.Yellow); + var original = Assert.Single(viewModel.ResultItems); + + viewModel.ApplyNotificationTheme(AdaptiveBackdropResolver.FromAppTheme(isDarkTheme: false)); + viewModel.ShowNotificationResult(["不替换"], 5, animate: false, preserveQuickDrawResult: true); + AssertInk(viewModel, Colors.Black); + Assert.Equal(original.DisplayText, Assert.Single(viewModel.ResultItems).DisplayText); + Assert.Equal(original.Tags, Assert.Single(viewModel.ResultItems).Tags); + + viewModel.ClearNotificationPresentation(); + AssertInk(viewModel, Colors.Yellow); + ReplaceStudentResults(viewModel, "手动闪抽"); + AssertInk(viewModel, Colors.Yellow); + } + + private QuickDrawPageViewModel CreateViewModel(bool darkAppTheme, bool useAccent = true) + { + var config = new MainConfigModel(); + config.Appearance.Theme = darkAppTheme ? ThemeMode.Dark : ThemeMode.Light; + config.QuickDrawSettings.DefaultClass = string.Empty; + config.QuickDrawSettings.AlgorithmId = "builtin.random"; + config.DefaultDrawSettings.AnimationColorTheme = useAccent ? AnimationColorThemeMode.Fixed : AnimationColorThemeMode.None; + config.DefaultDrawSettings.AnimationFixedColor = Colors.Yellow; + var handler = new MainConfigHandler(NullLogger.Instance, new TestConfigService(config)); + // Sampling/commit services are unused by presentation; disposal only stops the idle audio service. + return new QuickDrawPageViewModel(handler, null!, null!, null!, null!, _audio, + NullLogger.Instance, null!, null!, null!, null!); + } + + private static void ReplaceStudentResults(QuickDrawPageViewModel viewModel, string name) + { + var method = typeof(QuickDrawPageViewModel).GetMethod("ReplaceResults", BindingFlags.Instance | BindingFlags.NonPublic) + ?? throw new InvalidOperationException("Student result replacement was not found."); + method.Invoke(viewModel, new object[] { new Student[] { new() { Name = name, Id = "13", Tags = "标签" } } }); + } + + private static void AssertInk(QuickDrawPageViewModel viewModel, Color expected) + { + var item = Assert.Single(viewModel.ResultItems); + Assert.Equal(expected, Assert.IsAssignableFrom(item.TextBrush).Color); + } + + public void Dispose() + { + _audio.Dispose(); + GetUtilsMethod("ResetDataRootForTests").Invoke(null, null); + if (Directory.Exists(_dataRoot)) + Directory.Delete(_dataRoot, recursive: true); + } + + private static MethodInfo GetUtilsMethod(string name) => + typeof(Utils).GetMethod(name, BindingFlags.Static | BindingFlags.NonPublic) + ?? throw new InvalidOperationException($"Utils.{name} was not found."); + + 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/QuickDrawResultGridLayoutTests.cs b/SecRandom.Core.Tests/QuickDrawResultGridLayoutTests.cs new file mode 100644 index 000000000..266c0d814 --- /dev/null +++ b/SecRandom.Core.Tests/QuickDrawResultGridLayoutTests.cs @@ -0,0 +1,64 @@ +using SecRandom.Core.Services.FloatingWindow; + +namespace SecRandom.Core.Tests; + +/// +/// 浮窗结果卡的自适应列数:4 人 2×2、6 人横向 3×2 / 窄高 2×3,且列数不会因为 +/// 长姓名把卡片撑宽而退化成竖着排。 +/// +public sealed class QuickDrawResultGridLayoutTests +{ + [Theory] + [InlineData(4, 1920, 1080, 200, 100, 2)] + [InlineData(6, 1920, 1080, 200, 100, 3)] + [InlineData(6, 1200, 1600, 200, 100, 2)] + [InlineData(4, 800, 1200, 200, 100, 2)] + [InlineData(5, 1920, 1080, 200, 100, 3)] + [InlineData(1, 1920, 1080, 200, 100, 1)] + public void 按屏幕宽高选择列数( + int itemCount, + double availableWidth, + double availableHeight, + double cardWidth, + double cardHeight, + int expectedColumns) + { + var columns = QuickDrawResultGridLayout.ResolveColumns( + itemCount, availableWidth, availableHeight, cardWidth, cardHeight); + + Assert.Equal(expectedColumns, columns); + } + + [Theory] + [InlineData(6, 3840, 1080, 200, 100, 3)] // 超宽屏也不把 6 人排成 4+2 + [InlineData(4, 300, 1000, 200, 100, 1)] // 宽度只够一张时允许单列 + [InlineData(7, 1920, 1080, 200, 100, 4)] // 3+3+1 的孤行补成 4+3 + public void 列数受宽度与末行平衡约束( + int itemCount, + double availableWidth, + double availableHeight, + double cardWidth, + double cardHeight, + int expectedColumns) + { + var columns = QuickDrawResultGridLayout.ResolveColumns( + itemCount, availableWidth, availableHeight, cardWidth, cardHeight); + + Assert.Equal(expectedColumns, columns); + } + + [Fact] + public void 高度装不下时优先加列减少行数() + { + // 3 列时 8 人要 3 行(600 DIP)超过 500 的可用高度;4 列只要 2 行。 + var columns = QuickDrawResultGridLayout.ResolveColumns(8, 800, 500, 100, 200); + + Assert.Equal(4, columns); + } + + [Fact] + public void 没有结果时不产生列() + { + Assert.Equal(0, QuickDrawResultGridLayout.ResolveColumns(0, 1920, 1080, 200, 100)); + } +} \ No newline at end of file diff --git a/SecRandom.Core.Tests/RandomNumberSettingsConfigTests.cs b/SecRandom.Core.Tests/RandomNumberSettingsConfigTests.cs new file mode 100644 index 000000000..b68d32d83 --- /dev/null +++ b/SecRandom.Core.Tests/RandomNumberSettingsConfigTests.cs @@ -0,0 +1,63 @@ +using SecRandom.Core.Enums.Configs; +using SecRandom.Core.Models.SubConfigs.Picking; +using SecRandom.Core.Services.Profiles; + +namespace SecRandom.Core.Tests; + +/// +/// The random-number page is the only place these defaults are edited, but imported settings can be +/// out of range. Normalize is the shared guard so the page and both draw entries agree on the bounds. +/// +public sealed class RandomNumberSettingsConfigTests +{ + [Fact] + public void DefaultsAreOneToOneFiftyWithTemporaryOnlyReset() + { + var settings = new RandomNumberSettingsConfig(); + + Assert.Equal(1, settings.RollCallRangeStart); + Assert.Equal(50, settings.RollCallRangeEnd); + Assert.Equal(1, settings.LotteryRangeStart); + Assert.Equal(50, settings.LotteryRangeEnd); + Assert.Equal(RandomNumberResetBehavior.TemporaryOnly, settings.ResetBehavior); + } + + [Fact] + public void NormalizeClampsNegativeStart() + { + var settings = new RandomNumberSettingsConfig + { + RollCallRangeStart = -5, + RollCallRangeEnd = 50 + }; + + Assert.True(settings.Normalize()); + Assert.Equal(0, settings.RollCallRangeStart); + Assert.Equal(50, settings.RollCallRangeEnd); + } + + [Fact] + public void NormalizeCapsEndAtTheMaximumSpan() + { + var settings = new RandomNumberSettingsConfig + { + LotteryRangeStart = 10, + LotteryRangeEnd = 500 + }; + + Assert.True(settings.Normalize()); + + var expectedEnd = 10 + RosterSelection.MaxNumberRangeSpan - 1; + Assert.Equal(expectedEnd, settings.LotteryRangeEnd); + } + + [Fact] + public void NormalizeReturnsFalseWhenValuesAlreadyFit() + { + var settings = new RandomNumberSettingsConfig(); + + Assert.False(settings.Normalize()); + Assert.Equal(1, settings.RollCallRangeStart); + Assert.Equal(50, settings.LotteryRangeEnd); + } +} \ No newline at end of file diff --git a/SecRandom.Core.Tests/RandomNumberStatisticsServiceTests.cs b/SecRandom.Core.Tests/RandomNumberStatisticsServiceTests.cs new file mode 100644 index 000000000..b989dea99 --- /dev/null +++ b/SecRandom.Core.Tests/RandomNumberStatisticsServiceTests.cs @@ -0,0 +1,151 @@ +using System.Text.Json; +using Microsoft.Extensions.Logging.Abstractions; +using SecRandom.Core.Abstraction; +using SecRandom.Core.Services.Stats; + +namespace SecRandom.Core.Tests; + +/// +/// Number draws never write roster history, so this store is the only durable record the overview and the +/// random-number settings page can read. It must survive a corrupt file and must never keep more than the +/// bounded recent list. +/// +public sealed class RandomNumberStatisticsServiceTests : IDisposable +{ + private readonly string _directory = + Path.Combine(Path.GetTempPath(), $"secrandom-random-number-{Guid.NewGuid():N}"); + + private string FilePath => Path.Combine(_directory, "stats.json"); + + private RandomNumberStatisticsService CreateService() => + new(NullLogger.Instance, FilePath); + + [Fact] + public void RecordAccumulatesRoundsAndDrawnNumbers() + { + var service = CreateService(); + + service.Record("roll_call", 1, 50, [7, 9]); + service.Record("lottery", 10, 20, [12]); + + var snapshot = service.Load(); + + Assert.Equal(2, snapshot.TotalRounds); + Assert.Equal(3, snapshot.TotalDrawnCount); + Assert.NotNull(snapshot.LastDrawAt); + Assert.Equal(2, snapshot.Recent.Count); + Assert.Equal("lottery", snapshot.Recent[0].Source); + Assert.Equal(new[] { 1, 50 }, new[] { snapshot.Recent[1].RangeStart, snapshot.Recent[1].RangeEnd }); + Assert.Equal(new[] { 7, 9 }, snapshot.Recent[1].Numbers); + Assert.Collection(snapshot.Ranges, + range => + { + Assert.Equal((1, 50), (range.RangeStart, range.RangeEnd)); + Assert.Equal(1, range.DrawCount); + }, + range => + { + Assert.Equal((10, 20), (range.RangeStart, range.RangeEnd)); + Assert.Equal(1, range.DrawCount); + }); + } + + [Fact] + public void EmptyResultIsNotRecorded() + { + var service = CreateService(); + + service.Record("roll_call", 1, 50, []); + + var snapshot = service.Load(); + Assert.Equal(0, snapshot.TotalRounds); + Assert.Empty(snapshot.Recent); + } + + [Fact] + public void SameRangeCountsEveryDrawWithoutKeepingTheResults() + { + var service = CreateService(); + + service.Record("roll_call", 1, 50, [7, 9]); + service.Record("lottery", 1, 50, [42]); + service.Record("roll_call", 10, 20, [12]); + + var snapshot = service.Load(); + + Assert.Equal(3, snapshot.TotalRounds); + Assert.Equal(2, snapshot.Ranges.Count); + Assert.Equal(2, snapshot.Ranges[0].DrawCount); + Assert.Equal((1, 50), (snapshot.Ranges[0].RangeStart, snapshot.Ranges[0].RangeEnd)); + Assert.Equal(1, snapshot.Ranges[1].DrawCount); + } + + [Fact] + public void RecentRecordsKeepOnlyTheNewestHundred() + { + var service = CreateService(); + + for (var number = 1; number <= RandomNumberStatistics.MaxRecentRecords + 5; number++) + service.Record("roll_call", 1, 500, [number]); + + var snapshot = service.Load(); + + Assert.Equal(RandomNumberStatistics.MaxRecentRecords + 5, snapshot.TotalRounds); + Assert.Equal(RandomNumberStatistics.MaxRecentRecords, snapshot.Recent.Count); + Assert.Equal(105, snapshot.Recent[0].Numbers[0]); + Assert.Equal(6, snapshot.Recent[^1].Numbers[0]); + } + + [Fact] + public void CorruptFileIsQuarantinedAndTreatedAsEmpty() + { + Directory.CreateDirectory(_directory); + File.WriteAllText(FilePath, "{ not json"); + var service = CreateService(); + + var snapshot = service.Load(); + + Assert.Equal(0, snapshot.TotalRounds); + Assert.False(File.Exists(FilePath)); + Assert.True(File.Exists(FilePath + ".corrupt")); + + // A subsequent commit starts a fresh, valid document. + service.Record("roll_call", 1, 10, [3]); + Assert.Equal(1, service.Load().TotalRounds); + } + + [Fact] + public void UnsupportedFormatIsQuarantined() + { + Directory.CreateDirectory(_directory); + File.WriteAllText(FilePath, + JsonSerializer.Serialize(new RandomNumberStatistics { Format = "unknown/v9" }, + ConfigServiceBase.JsonOptions)); + + var snapshot = CreateService().Load(); + + Assert.Equal(0, snapshot.TotalRounds); + Assert.True(File.Exists(FilePath + ".corrupt")); + } + + [Fact] + public void ClearResetsTotalsAndRecent() + { + var service = CreateService(); + service.Record("roll_call", 1, 50, [4]); + + service.Clear(); + + var snapshot = service.Load(); + Assert.Equal(0, snapshot.TotalRounds); + Assert.Equal(0, snapshot.TotalDrawnCount); + Assert.Null(snapshot.LastDrawAt); + Assert.Empty(snapshot.Recent); + } + + public void Dispose() + { + if (Directory.Exists(_directory)) + Directory.Delete(_directory, recursive: true); + } +} \ No newline at end of file diff --git a/SecRandom.Core.Tests/RosterDigestTests.cs b/SecRandom.Core.Tests/RosterDigestTests.cs index e297ee1d9..f400d7f5a 100644 --- a/SecRandom.Core.Tests/RosterDigestTests.cs +++ b/SecRandom.Core.Tests/RosterDigestTests.cs @@ -48,6 +48,38 @@ public void PrizeDigestFollowsNameIdentityWeightAndCount() Assert.Equal(baseline, RosterDigest.Compute(new PrizeList { Prizes = [prize] })); } + [Fact] + public void SaltMakesTheSameRosterDigestDifferentPerProof() + { + var student = new Student { RecordId = Guid.Parse("11111111-1111-1111-1111-111111111111"), Id = "01", Name = "张三" }; + StudentList list = new() { Students = [student] }; + byte[] firstSalt = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]; + byte[] secondSalt = [16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]; + + var first = RosterDigest.Compute(list, firstSalt); + var second = RosterDigest.Compute(list, secondSalt); + + // Cross-proof joinability is exactly what the salt removes: two draws from one list must not look like + // the same roster to someone holding both files. + Assert.NotEqual(first, second); + // The digest stays recomputable, because the salt ships inside the proof. + Assert.Equal(first, RosterDigest.Compute(list, firstSalt)); + // And it still follows the mapping rather than the salt alone. + student.Name = "李四"; + Assert.NotEqual(first, RosterDigest.Compute(list, firstSalt)); + } + + [Fact] + public void UnsaltedDigestStaysTheLegacyV3Format() + { + var student = new Student { RecordId = Guid.Parse("11111111-1111-1111-1111-111111111111"), Id = "01", Name = "张三" }; + StudentList list = new() { Students = [student] }; + + // v3 proofs already on disk carry this value; the overload without a salt must keep deriving it. + Assert.Equal(RosterDigest.Compute(list), RosterDigest.Compute(list, [])); + Assert.NotEqual(RosterDigest.Compute(list), RosterDigest.Compute(list, [0])); + } + [Fact] public void StudentAndPrizeRostersDoNotShareADigest() { 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/SettingsMarkupTests.cs b/SecRandom.Core.Tests/SettingsMarkupTests.cs index 3f95f32d3..294661b70 100644 --- a/SecRandom.Core.Tests/SettingsMarkupTests.cs +++ b/SecRandom.Core.Tests/SettingsMarkupTests.cs @@ -279,7 +279,7 @@ public void QuickDrawWindowPresentationFollowsTheBuiltInNotificationService() "SecRandom/ViewModels/MainPages/QuickDrawPageViewModel.cs")); Assert.Contains("UsesBuiltInNotificationService(NotificationSettingsType.QuickDraw)", appSource, StringComparison.Ordinal); - Assert.Contains("StartAuthorizedTriggeredDrawAsync()", appSource, StringComparison.Ordinal); + Assert.Contains("StartAuthorizedTriggeredDrawAsync(count)", appSource, StringComparison.Ordinal); Assert.Contains("BeginBuiltInNotificationPresentationAsync(", viewModelSource, StringComparison.Ordinal); Assert.Contains("skipPreview = !showBuiltInNotificationAnimation;", viewModelSource, StringComparison.Ordinal); } @@ -448,8 +448,9 @@ public void UsbBindingDialogUsesTabsAndSingleSelectionDeviceRows() Assert.Contains("device.DisplayName", source, StringComparison.Ordinal); Assert.Contains("device.DeviceId", source, StringComparison.Ordinal); Assert.Contains("device.HardwareName", source, StringComparison.Ordinal); - Assert.Contains("!device.IsBound", source, StringComparison.Ordinal); - Assert.Contains("device.IsBound", source, StringComparison.Ordinal); + Assert.Contains("device.BindingId is null", source, StringComparison.Ordinal); + Assert.Contains("device.BindingId is not null", source, StringComparison.Ordinal); + Assert.Contains("SR.C_UsbDisconnected", source, StringComparison.Ordinal); Assert.Contains("new UsbBindingResult(device.DeviceId, null)", source, StringComparison.Ordinal); Assert.Contains("action.Text = isBinding ? SR.C_Bind : SR.C_Unbind", source, StringComparison.Ordinal); Assert.Contains("action.DialogResult = isBinding ? \"bind\" : \"unbind\"", source, StringComparison.Ordinal); @@ -490,6 +491,75 @@ public void SettingsPageCodeBehindLoadsItsMarkup(string pageName) Assert.Contains("InitializeComponent();", source, StringComparison.Ordinal); } + [Theory] + [InlineData("SecRandom/Views/SettingsPages/Picking/RollCallDrawSettingsPage.axaml")] + [InlineData("SecRandom/Views/SettingsPages/Picking/QuickDrawSettingsPage.axaml")] + [InlineData("SecRandom/Views/SettingsPages/Picking/LotteryDrawSettingsPage.axaml")] + [InlineData("SecRandom/Views/SettingsPages/Picking/DefaultDrawSettingsPage.axaml")] + public void DrawModeDropdownListsOnlyRepeatPolicies(string relativePath) + { + string markup = File.ReadAllText(GetRepositoryPath(relativePath)); + + // 「抽取模式」只回答重复记录怎么处理;编排抽取属于「抽取方式」,不能重新出现在这一行里。 + int card = markup.IndexOf("x:Name=\"S_DrawMode\"", StringComparison.Ordinal); + Assert.True(card >= 0, $"{relativePath} must keep the S_DrawMode card."); + int end = markup.IndexOf("", card, StringComparison.Ordinal); + Assert.True(end > card, $"{relativePath} must close the S_DrawMode card."); + + string block = markup[card..end]; + Assert.DoesNotContain("O_Orchestrated", block, StringComparison.Ordinal); + Assert.Equal(3, block.Split("= 0, $"{markupPath} must keep the S_DrawMode card."); + int end = markup.IndexOf("", card, StringComparison.Ordinal); + Assert.True(end > card, $"{markupPath} must close the S_DrawMode card."); + + string block = markup[card..end]; + Assert.Contains("SelectedIndex=\"{Binding Settings.SampledDrawMode}\"", block, StringComparison.Ordinal); + Assert.DoesNotContain("IsVisible", block, StringComparison.Ordinal); + } + + [Theory] + [InlineData("SecRandom/Views/SettingsPages/Picking/RollCallDrawSettingsPage.axaml", + "SecRandom/Views/SettingsPages/Picking/RollCallDrawSettingsPage.axaml.cs")] + [InlineData("SecRandom/Views/SettingsPages/Picking/QuickDrawSettingsPage.axaml", + "SecRandom/Views/SettingsPages/Picking/QuickDrawSettingsPage.axaml.cs")] + public void OnlyTheFairDrawPolicyCardHidesInOrchestration(string markupPath, string codeBehindPath) + { + string source = File.ReadAllText(GetRepositoryPath(codeBehindPath)); + + // 公平抽取策略对编排确实没有意义,这一张卡仍按抽取方式和算法隐藏。 + Assert.Contains("IsVisible = !DrawModeSelection.IsOrchestrated(Settings.DrawMode)", source, + StringComparison.Ordinal); + + string markup = File.ReadAllText(GetRepositoryPath(markupPath)); + Assert.Contains("x:Name=\"S_FairDrawMode\"", markup, StringComparison.Ordinal); + } + private static string GetDefaultNotificationMarkupPath() { return GetRepositoryPath( diff --git a/SecRandom.Core.Tests/TabletControlHostTests.cs b/SecRandom.Core.Tests/TabletControlHostTests.cs index 20ecd5078..bd6c2ce7b 100644 --- a/SecRandom.Core.Tests/TabletControlHostTests.cs +++ b/SecRandom.Core.Tests/TabletControlHostTests.cs @@ -23,6 +23,11 @@ namespace SecRandom.Core.Tests; /// !isMobile 判断,一旦有人把某个分支改回按平台判断,这些断言先红。 /// /// +/// 平板是**纯控制台**:它只登录账号、看地点/年级/班级并下发抽取,不做被控节点 +/// (不占班、不接配对码、不显示集控设置页),所以平板与手机一样走解锁闸门; +/// 这条产品边界由 AppHostShape.RunsControlNode 是 !isMobile 保证。 +/// +/// /// 为什么不真的跑一遍 BuildHost 再断言 DI:PagesRegistryService 是**进程级静态**集合, /// 同一进程里建第二个 Host 会以"页面 id 已被占用"抛异常,而桌面/平板/手机三种形态必须各建一次; /// 再加上 BuildHost 会拉起插件管理器与整套 Avalonia 服务,单测里跑不动。 @@ -39,7 +44,7 @@ public sealed class TabletControlHostTests [Theory] // isMobile 桌面主界面 | 是移动 是平板 手机壳 跑节点 解锁闸门 侧栏页 底部档 默认隐藏 [InlineData(false, false, false, false, false, true, false, true, false, true)] // 桌面 - [InlineData(true, true, true, true, false, true, false, true, false, false)] // 平板 + [InlineData(true, true, true, true, false, false, true, true, false, false)] // 平板(纯控制台) [InlineData(true, false, true, false, true, false, true, false, true, false)] // 手机 public void 宿主形态_三种形态的角色矩阵( bool isMobile, @@ -109,20 +114,21 @@ public sealed class TabletControlHostTests } [Fact] - public void 宿主形态_平板用真闸门而手机用解锁闸门() + public void 宿主形态_平板与手机都是纯控制台用解锁闸门() { var tablet = AppHostShape.Resolve(isMobile: true, usesDesktopMainView: true); var phone = AppHostShape.Resolve(isMobile: true, usesDesktopMainView: false); var desktop = AppHostShape.Resolve(isMobile: false, usesDesktopMainView: false); - // 硬约束:平板上有真的集控节点,因此必须用真闸门——用解锁闸门会让远程锁定失效、本地抽取被静默放行。 - Assert.False(tablet.UsesUnlockedDrawGate); - Assert.True(tablet.RunsControlNode); + // 平板不做被控节点:没有节点就没有真闸门,否则平板上会多出一把自己控制不了的锁。 + Assert.True(tablet.UsesUnlockedDrawGate); + Assert.False(tablet.RunsControlNode); - // 反过来:手机没有节点,用真闸门等于凭空多出一个自己控制不了的锁。 + // 手机同理:没有节点,用真闸门等于凭空多出一个自己控制不了的锁。 Assert.True(phone.UsesUnlockedDrawGate); Assert.False(phone.RunsControlNode); + // 桌面才是唯一被控节点,必须用真闸门——用解锁闸门会让远程锁定失效、本地抽取被静默放行。 Assert.False(desktop.UsesUnlockedDrawGate); Assert.True(desktop.RunsControlNode); } @@ -214,10 +220,12 @@ public sealed class TabletControlHostTests source, StringComparison.Ordinal); - // ViewModel 必须注册在**共享**分支,并且拿得到本机节点身份(手机没有节点 → GetService 返回 null, - // 设备列表里一台都不标"本机")。它原来只写在 `if (isMobile)` 里,桌面因此解析不到。 + // ViewModel 必须注册在**共享**分支:手机与平板都只有账号控制台,桌面则同时是被控节点。 + // 它原来只写在 `if (isMobile)` 里,桌面因此解析不到;现在拿的是账号控制台客户端, + // 不再需要本机节点身份(设备列表只用班级占班设备,不标"本机")。 Assert.Contains("new MobileRemoteDrawViewModel(", source, StringComparison.Ordinal); - Assert.Contains("provider.GetService()", source, StringComparison.Ordinal); + Assert.Contains("provider.GetRequiredService()", source, StringComparison.Ordinal); + Assert.Contains("provider.GetRequiredService()", source, StringComparison.Ordinal); var mobileOnlyViews = SectionOf(source, "// 杂项 Views", "// 界面 Views"); Assert.DoesNotContain("MobileRemoteDrawViewModel", mobileOnlyViews, StringComparison.Ordinal); } @@ -350,18 +358,23 @@ public sealed class TabletControlHostTests { var xaml = File.ReadAllText(GetRepositoryPath(@"SecRandom/Views/Mobile/MobileRemoteDrawPage.axaml")); - // 结构断言:结果区(DrawnMembers 所在的那个 Border)必须出现在第一个控制项之前。 + // 结构断言:顶部结果区(DrawnMembers 所在的那个 Border)必须出现在控制区之前。 var resultIndex = xaml.IndexOf("ViewModel.DrawnMembers", StringComparison.Ordinal); - var firstControlIndex = xaml.IndexOf("Resources.RD_Kind", StringComparison.Ordinal); - Assert.True(resultIndex > 0 && firstControlIndex > 0, "找不到结果区或第一个控制项"); + var controlIndex = xaml.IndexOf("============ 控制区:地点", StringComparison.Ordinal); + Assert.True(resultIndex > 0 && controlIndex > 0, "找不到结果区或控制区"); Assert.True( - resultIndex < firstControlIndex, - $"手机页结果区必须排在控制项之前(result={resultIndex}, firstControl={firstControlIndex})"); + resultIndex < controlIndex, + $"手机页结果区必须排在控制区之前(result={resultIndex}, control={controlIndex})"); // 结果区封顶且可滚动:结果多时不许把下面的控制项顶出屏幕。 Assert.Contains("MaxHeight=\"200\"", xaml, StringComparison.Ordinal); Assert.Contains("VerticalScrollBarVisibility=\"Auto\"", xaml, StringComparison.Ordinal); + // 结果区不放刷新:刷新属于控制区,同一动作只在一个地方出现。 + var resultArea = xaml[..controlIndex]; + Assert.DoesNotContain("RefreshCommand", resultArea, StringComparison.Ordinal); + Assert.Contains("RefreshCommand", xaml[controlIndex..], StringComparison.Ordinal); + // 抽取按钮下方不再重复结果/失败文案(只留进行中状态),也照样不放刷新入口。 var drawButtonIndex = xaml.IndexOf("ViewModel.DrawCommand", StringComparison.Ordinal); Assert.True(drawButtonIndex > 0, "找不到抽取按钮"); @@ -370,11 +383,6 @@ public sealed class TabletControlHostTests Assert.DoesNotContain("ViewModel.DrawnMembers", belowDrawButton, StringComparison.Ordinal); Assert.DoesNotContain("ResultPlaceholderTitle", belowDrawButton, StringComparison.Ordinal); Assert.Contains("ViewModel.IsBusy", belowDrawButton, StringComparison.Ordinal); - - // 顶部结果区不放刷新(刷新在控制区)。 - var resultArea = xaml[..firstControlIndex]; - Assert.DoesNotContain("RefreshCommand", resultArea, StringComparison.Ordinal); - Assert.Contains("RefreshCommand", xaml[firstControlIndex..], StringComparison.Ordinal); } [Fact] @@ -421,42 +429,6 @@ private static string ExtractResourceValue(string resx, string key) return resx[(valueStart + "".Length)..valueEnd]; } - [Fact] - public void 条件UI_两个视图都按能力闸门显示且取值来自设备派生() - { - var desktop = File.ReadAllText(GetRepositoryPath(@"SecRandom/Views/MainPages/RemoteDrawPage.axaml")); - var phone = File.ReadAllText(GetRepositoryPath(@"SecRandom/Views/Mobile/MobileRemoteDrawPage.axaml")); - - foreach (var xaml in new[] { desktop, phone }) - { - // 条件区只在**设备声明了 draw.trigger.conditions**时显示;老设备显示一句说明,绝不假装能筛。 - Assert.Contains("IsVisible=\"{Binding ViewModel.ShowsLotteryConditions}\"", xaml, StringComparison.Ordinal); - Assert.Contains("ViewModel.ShowsLotteryConditionsUnsupported", xaml, StringComparison.Ordinal); - Assert.Contains("Resources.RD_ConditionsUnsupported", xaml, StringComparison.Ordinal); - - // 取值全部来自设备已读回来的数据,没有自由文本入口。 - Assert.Contains("ItemsSource=\"{Binding ViewModel.PrizeTags}\"", xaml, StringComparison.Ordinal); - Assert.Contains("ItemsSource=\"{Binding ViewModel.RecipientListNames}\"", xaml, StringComparison.Ordinal); - Assert.Contains("ViewModel.RecipientGenderOptions", xaml, StringComparison.Ordinal); - Assert.Contains("ViewModel.RecipientGroupOptions", xaml, StringComparison.Ordinal); - Assert.DoesNotContain("Resources.RD_LotteryNoScope", xaml, StringComparison.Ordinal); - } - - // 三语齐全(条件区标题、标签、说明、发放对象、不指定、老设备说明)。 - foreach (var resource in new[] { "Resources.resx", "Resources.en-US.resx", "Resources.ja-JP.resx" }) - { - var text = File.ReadAllText(GetRepositoryPath(Path.Combine("SecRandom/Langs/Mobile", resource))); - foreach (var key in new[] - { - "RD_Conditions", "RD_PrizeTags", "RD_PrizeTagsHint", - "RD_Recipient", "RD_RecipientNone", "RD_ConditionsUnsupported" - }) - { - Assert.Contains($"name=\"{key}\"", text, StringComparison.Ordinal); - } - } - } - [Fact] public void 桌面版式_结果区只绑回执派生的成员() { @@ -469,10 +441,10 @@ private static string ExtractResourceValue(string resx, string key) Assert.Contains("IsVisible=\"{Binding !ViewModel.HasResult}\"", xaml, StringComparison.Ordinal); Assert.Contains("IsVisible=\"{Binding ViewModel.HasEmptyState}\"", xaml, StringComparison.Ordinal); - // VM 的 DrawnMembers 只有一个来源:回执(detail.drawn)解析出来的成员。 + // VM 的 DrawnMembers 只有一个来源:回执(payload.drawn)解析出来的成员。 var viewModelSource = File.ReadAllText(GetRepositoryPath(@"SecRandom/ViewModels/Mobile/MobileRemoteDrawViewModel.cs")); - Assert.Contains("foreach (var member in finished.DrawnMembers())", viewModelSource, StringComparison.Ordinal); - Assert.Contains("DrawnMembers.Add(member);", viewModelSource, StringComparison.Ordinal); + Assert.Contains("ApplyCommandResult(result);", viewModelSource, StringComparison.Ordinal); + Assert.Contains("DrawnMembers.Add(new ControlDrawnMember(id, name));", viewModelSource, StringComparison.Ordinal); } [Fact] diff --git a/SecRandom.Core.Tests/TextLibraryTests.cs b/SecRandom.Core.Tests/TextLibraryTests.cs index 618af3c1f..e1655d768 100644 --- a/SecRandom.Core.Tests/TextLibraryTests.cs +++ b/SecRandom.Core.Tests/TextLibraryTests.cs @@ -1,6 +1,7 @@ using Microsoft.Extensions.Logging.Abstractions; using SecRandom.Core.Models.Notification; using SecRandom.Core.Services.Notification; +using System.Globalization; namespace SecRandom.Core.Tests; @@ -560,6 +561,69 @@ public void ParseJson_FailsOnBlankContent() Assert.False(TextLibraryImporter.ParseJson(" ").Success); } + // ---- AI 提示词 ---- + + [Fact] + public void Build_WritesEnglishInstructionsInEveryInterfaceLanguage() + { + foreach (var culture in new[] { "zh-CN", "en-US", "ja-JP" }) + { + string prompt = TextLibraryPrompt.Build(CultureInfo.GetCultureInfo(culture)); + + Assert.All(prompt, c => Assert.True(c < 128, $"{culture} 的提示词正文出现了非 ASCII 字符:{c}")); + Assert.DoesNotContain("__OUTPUT_LANGUAGE__", prompt, StringComparison.Ordinal); + Assert.Contains("SecRandom", prompt, StringComparison.Ordinal); + Assert.Contains("What kind of texts do you need?", prompt, StringComparison.Ordinal); + Assert.Contains("How many texts do you need? (1 to 500)", prompt, StringComparison.Ordinal); + Assert.Contains("200", prompt, StringComparison.Ordinal); + Assert.Contains("14000", prompt, StringComparison.Ordinal); + Assert.Contains("{result}", prompt, StringComparison.Ordinal); + } + } + + [Fact] + public void Build_SwitchesOnlyTheOutputLanguage() + { + string english = TextLibraryPrompt.Build(CultureInfo.GetCultureInfo("en-US")); + string chinese = TextLibraryPrompt.Build(CultureInfo.GetCultureInfo("zh-CN")); + string japanese = TextLibraryPrompt.Build(CultureInfo.GetCultureInfo("ja-JP")); + + Assert.Contains("Reply to me in English.", english, StringComparison.Ordinal); + Assert.Contains("Reply to me in Simplified Chinese.", chinese, StringComparison.Ordinal); + Assert.Contains("Reply to me in Japanese.", japanese, StringComparison.Ordinal); + Assert.Contains("in English.", english, StringComparison.Ordinal); + Assert.Contains("in Simplified Chinese.", chinese, StringComparison.Ordinal); + Assert.Contains("in Japanese.", japanese, StringComparison.Ordinal); + Assert.Equal(english.Replace("in English.", "in Simplified Chinese."), chinese); + Assert.Equal(english.Replace("in English.", "in Japanese."), japanese); + } + + [Fact] + public void Build_AcceptsNullCultureAsEnglish() + { + Assert.Equal( + TextLibraryPrompt.Build(CultureInfo.GetCultureInfo("en-US")), + TextLibraryPrompt.Build(null)); + } + + [Fact] + public void Build_TemplateIsPasteableJson() + { + string prompt = TextLibraryPrompt.Build(CultureInfo.GetCultureInfo("en-US")); + const string fence = "```"; + int start = prompt.IndexOf("```json", StringComparison.Ordinal); + Assert.True(start >= 0, "提示词缺少 json 代码块"); + start += "```json".Length; + int end = prompt.IndexOf(fence, start, StringComparison.Ordinal); + Assert.True(end > start, "提示词的 json 代码块没有闭合"); + + var result = TextLibraryImporter.ParseJson(prompt[start..end].Trim()); + + Assert.True(result.Success, string.Join(Environment.NewLine, result.Errors)); + Assert.Equal(2, result.Templates.Count); + Assert.Empty(result.Warnings); + } + // ---- 清单 / 表格导入 ---- [Fact] diff --git a/SecRandom.Core.Tests/UpdateSourceResolverTests.cs b/SecRandom.Core.Tests/UpdateSourceResolverTests.cs new file mode 100644 index 000000000..a79ee854b --- /dev/null +++ b/SecRandom.Core.Tests/UpdateSourceResolverTests.cs @@ -0,0 +1,87 @@ +using System.Net.Http; +using System.Text; +using SecRandom.Services.Updates; +using SecRandom.Shared.Updates; + +namespace SecRandom.Core.Tests; + +public sealed class UpdateSourceResolverTests +{ + [Fact] + public void Order_puts_fastest_reachable_source_first_and_unreachable_last() + { + var order = UpdateSourceResolver.Order( + [ + new UpdateSourceProbe(UpdateSource.Sectl, TimeSpan.MaxValue, false), + new UpdateSourceProbe(UpdateSource.GitHubMirror, TimeSpan.FromMilliseconds(120), true), + new UpdateSourceProbe(UpdateSource.GitHub, TimeSpan.FromMilliseconds(30), true) + ]); + + Assert.Equal(new[] { UpdateSource.GitHub, UpdateSource.GitHubMirror, UpdateSource.Sectl }, order); + } + + [Fact] + public void Order_keeps_default_priority_when_every_source_is_unreachable() + { + // ResolveAsync 按 DefaultOrder 发起探测,排序对相同延迟保持稳定, + // 所以全部不可达时仍然回落到默认优先级。 + var order = UpdateSourceResolver.Order( + [ + new UpdateSourceProbe(UpdateSource.Sectl, TimeSpan.MaxValue, false), + new UpdateSourceProbe(UpdateSource.GitHubMirror, TimeSpan.MaxValue, false), + new UpdateSourceProbe(UpdateSource.GitHub, TimeSpan.MaxValue, false) + ]); + + Assert.Equal(UpdateSourceResolver.DefaultOrder, order); + } + + [Fact] + public async Task Manual_choice_is_tried_first_and_keeps_a_fallback_chain() + { + using var httpClient = new HttpClient(); + var resolver = new UpdateSourceResolver(httpClient); + + var order = await resolver.ResolveAsync(UpdateSource.GitHubMirror, false, CancellationToken.None); + + Assert.Equal( + new[] { UpdateSource.GitHubMirror, UpdateSource.Sectl, UpdateSource.GitHub }, + order); + } + + [Fact] + public async Task Auto_falls_back_to_default_priority_when_no_probe_succeeds() + { + using var httpClient = new HttpClient(new FailingHandler()); + var resolver = new UpdateSourceResolver(httpClient); + + var order = await resolver.ResolveAsync(UpdateSource.Auto, true, CancellationToken.None); + + Assert.Equal(UpdateSourceResolver.DefaultOrder, order); + } + + [Theory] + [InlineData("{\"tag\":\"v3.1.5\"}", "v3.1.5")] + [InlineData("{\"tag\":null}", null)] + [InlineData("{}", null)] + [InlineData("{\"tag\":\" \"}", null)] + public void ReadTag_treats_an_empty_channel_as_no_version(string json, string? expected) + { + Assert.Equal(expected, SectlSoftwareApi.ReadTag(Encoding.UTF8.GetBytes(json))); + } + + [Theory] + [InlineData(UpdateChannel.Release, "stable")] + [InlineData(UpdateChannel.Beta, "beta")] + [InlineData(UpdateChannel.Alpha, "alpha")] + public void Api_channel_names_match_the_platform_api(UpdateChannel channel, string expected) + { + Assert.Equal(expected, SectlSoftwareApi.ToApiChannel(channel)); + } + + private sealed class FailingHandler : HttpMessageHandler + { + protected override Task SendAsync( + HttpRequestMessage request, CancellationToken cancellationToken) + => throw new HttpRequestException("offline"); + } +} \ No newline at end of file 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.Tests/VerificationKernelTests.cs b/SecRandom.Core.Tests/VerificationKernelTests.cs index 807ea2367..37b19e14a 100644 --- a/SecRandom.Core.Tests/VerificationKernelTests.cs +++ b/SecRandom.Core.Tests/VerificationKernelTests.cs @@ -44,6 +44,18 @@ public void DrawProof_UsesAlgorithmEngineVersionAndReadsLegacyKernelVersion() Assert.Equal("1.0.0", legacy!.LegacyKernelVersion); } + [Fact] + public void DrawProof_VersionsTheOrchestratedGenerationSeparately() + { + // 编排放不进 3.5.0 的版本链:现网 3.5 验证器既不认识 SequentialOrder 也不认识 profile 19/20, + // 所以只有编排证明盖 3.6.0,普通抽取继续盖 3.5.0,普通抽取在服务端升级期间照常认证。 + Assert.Equal("3.5.0", VerificationWireCodec.GetEngineVersion(VerificationSamplingMode.HistoryBalancedWeighted)); + Assert.Equal("3.5.0", VerificationWireCodec.GetEngineVersion(VerificationSamplingMode.InventoryPermutation)); + Assert.Equal("3.5.0", VerificationWireCodec.GetEngineVersion(VerificationSamplingMode.WeightedWithoutReplacement)); + Assert.Equal("3.6.0", VerificationWireCodec.GetEngineVersion(VerificationSamplingMode.SequentialOrder)); + Assert.Equal("3.6.0", VerificationWireCodec.OrchestratedAlgorithmEngineVersion); + } + [Fact] public void Draw_IsStableAcrossCandidateOrder() { diff --git a/SecRandom.Core/AGENTS.md b/SecRandom.Core/AGENTS.md index e777453aa..bd1973753 100644 --- a/SecRandom.Core/AGENTS.md +++ b/SecRandom.Core/AGENTS.md @@ -27,7 +27,9 @@ SecRandom.Core/ ├── Styles/ # Modular shared style files, including RichTextStyles for Markdown.Avalonia ├── StylesBase.axaml # Shared style hub imported by app ├── Services/Draw/ # Fair/random draw engine, filters, commit coordinator, shared repeat/candidate rules +├── Services/FloatingWindow/ # 浮窗长按快抽的纯计算规则(进度、蓝→绿环色、行序、落位夹紧) ├── 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 +57,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 and keeps the gated pool drawable, `FairDrawMode.RandomFirst` drops the gate and weights by the least-drawn member with a staged lead ceiling: one draw while anybody is still undrawn (so nobody repeats before the first full round), two draws afterwards, so a three-draw-vs-zero history cannot be produced), one shared lead-deficit weight function, 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 +70,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. | @@ -89,6 +91,7 @@ SecRandom.Core/ - `IControlDrawGate` is consumed by the app-layer `LinkageDrawCoordinator` on every host, so it must always be resolvable: desktop registers the real `ControlDrawGateService`, and a host without a local control node (the mobile console) registers the neutral `UnlockedControlDrawGate`. Never use the unlocked gate on desktop — a missing real gate has to fail loudly instead of silently unlocking every draw. - `IProfileService.LoadStudentProfile(name)` switches the app-layer active point-call student list and matching history; callers should use it instead of constructing profile configs directly when changing the active roll-call list. - Profile startup/switching validates nonempty names with `ProfileConfigBase` before path access or saving the active profile. Archive settings validation checks roll-call/quick-draw `DefaultClass` and lottery `DefaultPool` before snapshots or commit; the exact empty string means no selection, not a file name. +- Lists and prize pools may all be deleted, so a profile-less runtime is a supported state. `ProfileService.SeedDefaultListsOnFirstRun()` writes the blank `default` profile only while `General.Basic.GuideCompleted == false` and the directory has no `*.json`; after onboarding `ResolveProfileName` returns `null` and the four profile configs stay `null` (`Current*` therefore `null`), which every nullable consumer already tolerates. An empty name passed to `LoadStudentProfile`/`LoadPrizeProfile` detaches the active profile (`Clear*Profile` saves it first when asked) rather than being an invalid call, and `ProfileCatalogManager.Delete{Student,Prize}List` relies on that after removing the last profile. `SetDefault{StudentList,PrizePool}` accepts an empty name to clear a default that no longer points at an existing file. Do not add a fallback that recreates `default` at startup: that would silently resurrect lists the user deleted. - Registration helpers are responsible for both keyed DI and `PagesRegistryService` metadata. - Build metadata is never generated inside Core: the platform head assembly carries it (root `AssemblyInfo.cs` plus `EnableGitInfoGenerator`), and every head publishes itself through `GlobalConstants.SetVersionAssembly` before any version value is read. Android has no managed entry point, so `Assembly.GetEntryAssembly()` is null there and the version would otherwise fall back to this library and render as `v0.0.0.0` across the settings title bar, `producer_version`, export file names, and telemetry. Keep the entry-assembly fallback for desktop and test hosts, and never reintroduce a Core-local `SecRandom.GitInfo` type. - `DrawEngine` is partial: keep filtering in `DrawEngine.Filter.cs`, weight math in `DrawEngine.WeightCalculator.cs`, @@ -98,23 +101,26 @@ SecRandom.Core/ - Draw fairness/repeat history for students and prizes must use `ProfileRecordIdentity`/`RecordId` first. Legacy `Id`/`Name` history fallback is only for backward compatibility and must stay ambiguity-safe. - Draw commits are coordinator-only: app sessions and page ViewModels must call `IDrawCommitService` (`DrawCommitCoordinator`) instead of pairing temporary-record writes with `IProfileService.Record*History`. The optional `drawRoundId` (and `drawMethod` on `RecordPrizeHistory`) parameters exist for coordinator use; a mid-commit failure rolls back through snapshot compensation, and commits serialize behind the coordinator gate. - Student fair-draw execution must support explicit internal policy snapshots. Desktop public `DrawEngine` methods stay byte-compatible by deriving a `DesktopConfigured` snapshot from live `MainConfigModel.FairDrawSettings`; mobile fair draws use the fixed `MobileDesktopDefaultsV1` snapshot and must not read persisted fair-setting values. -- Verification proof inputs commit a `VerificationSamplingMode` and `VerificationAlgorithmProfile`. The profile must match the draw kind and sampler: fair/random students use history-balanced or unit-weight sampling when no behind-scene rule is active, student behind-scene weighting uses a dedicated profile, Count lottery uses equal-probability partial inventory permutation without behind-scene rules, and Pan or an internal-rule fallback uses weighted-without-replacement. Any internal rule, including zero-probability exclusions, must stay visible in the ordinary verification draw's anonymous audit payload. Formal notarization is the explicit exception: it must ignore internal rules completely and omit them from its locked input and audit payload. +- Verification proof inputs commit a `VerificationSamplingMode` and `VerificationAlgorithmProfile`. The profile must match the draw kind and sampler: fair/random students use history-balanced or unit-weight sampling when no behind-scene rule is active, student behind-scene weighting uses a dedicated profile, Count lottery uses equal-probability partial inventory permutation without behind-scene rules, and Pan or an internal-rule fallback uses weighted-without-replacement. Any internal rule, including zero-probability exclusions, must stay visible in the ordinary verification draw's anonymous audit payload. Formal notarization is the explicit exception: it must ignore internal rules completely and omit them from its locked input and audit payload. An orchestrated draw is the same kind of exception on the sampler axis: `StudentOrchestrated`/`LotteryOrchestrated` (19/20) is compatible only with `VerificationSamplingMode.SequentialOrder` (4), which takes the arranged position out of the weight slot (`1..count`, dense and unique) and consumes no random material, and its input may never be built by the sampled `Create*VerificationInput` entry points — they throw for `DrawMode.Orchestrated` because a sampled proof would replay as a random draw. The mode's wire token comes from `Enums/Configs/DrawModeCatalog.cs`, never from a call-site literal. The engine version is split in `Services/Verification/VerificationWireCodec.cs`: ordinary draws keep stamping `AlgorithmEngineVersion` (3.5.0) while only `SequentialOrder` stamps `OrchestratedAlgorithmEngineVersion` (3.6.0) through `GetEngineVersion(samplingMode)`, because a 3.5 verifier rejects an unknown generation outright and the two features must be able to ship in either order without breaking the other's attestation. - Config handlers derive from `ConfigHandlerBase`; config model defaults should be safe without existing data 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. - V2-parity settings models that are shared by app settings pages but not yet backed by services live directly under `Models/SubConfigs/` and hang off `MainConfigModel` until their runtime service boundaries settle. `MoreSettingsConfig` also owns built-in draw page chrome toggles such as roll-call/lottery control panel placement and visibility. - Linkage enums and course snapshot DTOs are UI-free Core contracts. The app owns CSES files, ClassIsland IPC, timers, and window behavior. Student draw APIs may accept an optional course name to project `HistoryItem.CourseName`; empty course input must retain global-history behavior. -- History record groups (`HistoryItem.HistoryGroup`, issue #294) are the second, orthogonal scope axis next to `CourseName`: `DrawEngine.Filter.FilterHistoryForScope` intersects both (an empty string leaves that axis unfiltered, so empty+empty is the legacy global read and must stay a zero-allocation fast path). The group is a **usage purpose**, not a property of a person, so it deliberately does **not** join `WeightCalculator.GetEnabledDimensionSelectors` (group/gender share-debt dimensions) — a group-scoped draw is just the existing weight math fed a narrower history cache. `historyGroup` is threaded as a trailing optional parameter through the draw entries, `IProfileService.Record*History`, `IDrawCommitService.*DrawCommit`, and `DrawEngine.Verification.Create*VerificationInput` (kept last so app-layer positional calls keep compiling). Temporary draw records are bucketed per history record group (`null` = unscoped bucket, `""` = default group, a name = that group) so a group-scoped draw's repeat limit counts exactly the set it can see; see the `DrawTemporaryRecordService` row for the rename/delete/reset rules. `Services/Profiles/HistoryGroupScope.cs` (`HistoryGroupScope.Resolve`) is the one place that turns a persisted default-group value into the runtime tri-state: feature off ⇒ `null`, blank value ⇒ `""` (the default record group), a name still present in `IHistoryGroupCatalog.GetGroupNames` ⇒ that name, a name that disappeared ⇒ `""` plus `ConfiguredGroupMissing` (deleting a group moves its records back to the default group, so narrowing to the default group is the truthful fallback), and an unreadable catalog ⇒ `null` rather than guessing. Group identity is the name itself (`HistoryGroupInfo` stores only `CreatedAt`/`LastUsedAt`, counts are derived), names are validated by `Services/Profiles/HistoryGroupName.cs` (32 chars, no control characters, `__x__` forms reserved including the `__break__` sentinel), and groups are separated per `Enums/HistoryGroupKind` (`RollCall`/`Lottery`). `IHistoryGroupCatalog.GetGroupNames` returns registered names ∪ names found on records, which is why no history-file migration exists. Moving records between groups is `IProfileCatalogManager.Move{Student,Prize}HistoryGroup` (marker-only; it must not fabricate a draw record or a `DrawRoundId`, and therefore does not go through `IDrawCommitService`). Old builds collapse every group back into the global history on read and then drop the markers on their next save, so downgrade is a silent semantic regression rather than an error. +- History record groups (`HistoryItem.HistoryGroup`, issue #294) are the second, orthogonal scope axis next to `CourseName`: `DrawEngine.Filter.FilterHistoryForScope` intersects both (an empty string leaves that axis unfiltered, so empty+empty is the legacy global read and must stay a zero-allocation fast path). The group is a **usage purpose**, not a property of a person, so it deliberately does **not** enter the weight math as a dimension — a group-scoped draw is just the shared lead-deficit weight function fed a narrower history cache. `historyGroup` is threaded as a trailing optional parameter through the draw entries, `IProfileService.Record*History`, `IDrawCommitService.*DrawCommit`, and `DrawEngine.Verification.Create*VerificationInput` (kept last so app-layer positional calls keep compiling). Temporary draw records are bucketed per history record group (`null` = unscoped bucket, `""` = default group, a name = that group) so a group-scoped draw's repeat limit counts exactly the set it can see; see the `DrawTemporaryRecordService` row for the rename/delete/reset rules. `Services/Profiles/HistoryGroupScope.cs` (`HistoryGroupScope.Resolve`) is the one place that turns a persisted default-group value into the runtime tri-state: feature off ⇒ `null`, blank value ⇒ `""` (the default record group), a name still present in `IHistoryGroupCatalog.GetGroupNames` ⇒ that name, a name that disappeared ⇒ `""` plus `ConfiguredGroupMissing` (deleting a group moves its records back to the default group, so narrowing to the default group is the truthful fallback), and an unreadable catalog ⇒ `null` rather than guessing. Group identity is the name itself (`HistoryGroupInfo` stores only `CreatedAt`/`LastUsedAt`, counts are derived), names are validated by `Services/Profiles/HistoryGroupName.cs` (32 chars, no control characters, `__x__` forms reserved including the `__break__` sentinel), and groups are separated per `Enums/HistoryGroupKind` (`RollCall`/`Lottery`). `IHistoryGroupCatalog.GetGroupNames` returns registered names ∪ names found on records, which is why no history-file migration exists. Moving records between groups is `IProfileCatalogManager.Move{Student,Prize}HistoryGroup` (marker-only; it must not fabricate a draw record or a `DrawRoundId`, and therefore does not go through `IDrawCommitService`). Old builds collapse every group back into the global history on read and then drop the markers on their next save, so downgrade is a silent semantic regression rather than an error. The **write** side is a separate entry point on the same type: `HistoryGroupScope.ResolveRecordGroup(string? configuredGroup, IReadOnlyList? availableGroupNames)` takes no `enabled` flag on purpose — the master switch only gates whether a selector may appear, never which group a record belongs to — and returns a non-null marker (blank ⇒ `""`, unreadable catalogue ⇒ the configured name rather than a silent move into the default group, a name that no longer exists ⇒ `""`). `StudentDrawCommit.RecordGroup` / `LotteryDrawCommit.RecordGroup` (+ `StudentRecordGroup` for the students a lottery round assigns, whose records land in the student history) carry it, `DrawCommitCoordinator` resolves `RecordGroup ?? HistoryGroup`, and every channel that can draw without a group scope (`RollCallSession`, `LotterySession`, `RollCallDrawService`, `LotteryDrawService`, `QuickDrawPageViewModel`) passes one, so turning the feature off can never fold 点名/闪抽/抽奖/编排 into one bucket. +- `ProfileCatalogManager.MoveHistoryGroup` rewrites markers only: `MoveIntoGroup` iterates the member-keyed `ObservableDictionary` and, when `sourceGroup` is non-null, skips every `HistoryItem` whose current `HistoryGroup` differs from it, so a group-filtered history page moves just the records it shows. The member is the selection unit (`RecordId` is shared by all of that member's records); `sourceGroup == null` preserves the whole-member behaviour and `""` targets the default group. No group registration happens for a scoped move that changed nothing. - Attached settings models under `Models/AttachedSettings/` may target students and prizes. `SpecificAnnouncementAttachedSettings` stores per-record TTS alias, prefix, and suffix; `DrawMusicAttachedSettings` stores per-record animation/result track IDs. App-layer controls/services render and consume both. `DrawSettingsConfigBase.VoiceAnnouncementEnabled` uses the existing default-and-per-draw override pattern; `VoiceSettings.VoiceEnable` remains the runtime total switch. The app-facing `ISpeechProvider` and `ISpeechAudioPlayer` contracts live under `Abstraction/Services` so voice acquisition remains separate from playback; synthesis stays at normal speed, while the single SoundFlow player applies the configured speed through pitch-preserving WSOLA time stretching. `VoiceSettingsConfig` also carries the OmniTTS engine-2 fields (`OmniTtsProvider`, `OmniTtsApiBaseUrl`, `OmniTtsModel`, `OmniTtsVoiceId`, `OmniTtsInstructions`); the engine int and per-provider default helpers live in the app-layer `OmniTtsSpeechProvider`, where Gemini native TTS wraps its 24 kHz PCM response as WAV before playback. API keys never enter this model (see `OmniTtsCredentialStore`). - Attached-settings presenter behavior separates editing from activation: the expander content should remain openable/editable even when `IsAttachSettingsEnabled` is false, while the switch only controls whether the saved settings take effect. - `MainConfigModel.General` is the canonical general-settings subtree. Legacy root `Basic` / `Backup` bridges may remain temporarily for backward-compatible callers and JSON migration, but new general config splits should be nested under `Models/SubConfigs/General/`. Privacy settings belong under `General.PrivacySettings`; keep Sentry upload (`SentryTelemetryEnabled`) separate from online status reporting (`OnlineStatusMode`). `General.PerformanceSettings.LowSpecMode` is the app's low-spec switch; Core only exposes the flag and the `IntroAnimationPolicy` gate, while the app layer decides what it turns off. - `Behaviors/IntroAnimationPolicy.IsEnabled` is the only supported way to suppress the page-intro and popup-intro animations. It must be read **before** `StackPanelIntroAnimationBehavior` latches an element: `StackPanelIntroAnimation.axaml` applies `Opacity=0` only to children whose `CanPlayAnimation` is already true, and the behavior never resets `CanPlayAnimation`/`IsAnimationPlayed` (they are one-way local values). Setting `IsIntroAnimationEnabled=false` after the style has been applied therefore leaves page content permanently invisible, so the policy is consulted only in `HandleIsIntroAnimationChanged` and `StartAnimation` is deliberately left ungated — an animation that has already started must always be allowed to finish. - Controls should keep `.axaml` and `.axaml.cs` side by side and expose reusable Avalonia properties/templates. +- `AnchorGridPicker` (`Controls/AnchorGridPicker.cs` + paired `Controls/AnchorGridPicker.axaml`) is the 3×3 dot-grid anchor chooser: it subclasses `UniformGrid` (from `Avalonia.Controls.Primitives`, not `Avalonia.Controls`) and builds nine real `Button`s in `NotificationWindowAnchorLayout.GridOrder`, so Tab, arrow-key movement, Enter/Space, tooltips and automation names all work without a bespoke input layer. `SelectedValue` is a `TwoWay`-by-default `int` DP whose class handler normalizes an out-of-range value to `Center` (the config model clamps the same way), and `Labels` is ordered like `GridOrder` because a dot only expresses direction — the caller shows the selected label as text. Its style file replaces the Fluent `Button` template through a plain `Style` setter for `Button.Template`; this **does** win over `FluentAvaloniaTheme`'s `ControlTheme` template (verified by rendering the control headless), so the cells carry no button chrome, and only the dot `Border` is themed (tertiary fill at low opacity, accent fill when `.selected`, accent ring on `:focus-visible`). Never switch the dot colors to hard-coded brushes: they follow the user's theme and accent color. +- `AnchorGridDropDown` (`Controls/AnchorGridDropDown.cs` + paired `Controls/AnchorGridDropDown.axaml`) is the ComboBox-shaped wrapper around that grid: the collapsed field shows `Labels[NotificationWindowAnchorLayout.ToCellIndex(SelectedValue)]` next to a chevron and keeps the Fluent `ComboBox` brushes, corner radius and 32px height, so replacing a real ComboBox does not change the field's look. Its `Button` flyout hosts an `AnchorGridPicker`; picking a dot writes `SelectedValue`, raised only through the picker's `SelectionCommitted` event (a real click or Enter/Space, never an arrow-key move), and hides the flyout — keyboard browsing therefore keeps the popup open, and the flyout focuses the currently selected cell when it opens. +- `AnchorGridPicker`'s nine anchors are `NotificationWindowPosition` values 0–8 and the persisted meaning is append-only (`Center`/`Top`/`Bottom`/`Left`/`Right` keep 0–4, the corners are 5–8). Every consumer — this control, `AnchorGridDropDown`, `NotificationFloatingWindowSettingsPage`, `App.TryResolveQuickDrawNotificationTargetRect` — must read `NotificationWindowAnchorLayout` instead of re-deriving the grid order or the horizontal/vertical anchor from the integer, so the cell a user clicks and the window geometry can never drift apart. - `TouchInputModeAssist` tracks the latest top-level pointer mode, and `TouchTextCommandBarFlyout` provides the touch-only horizontal cut/copy/paste editor toolbar with overflow undo/redo/select-all. `Styles/TouchTextCommandBarFlyout.axaml` applies it to `TextBox` only while touch mode is active; do not replace mouse/keyboard text context menus. - Shared styles are modular; add new broad styles under `Styles/` and include from `StylesBase.axaml`. - `MultiComboBox` (`SecRandom.Core/Controls/MultiComboBox.cs`, `MultiComboBoxItem.cs`) is the in-house multi-select control; its theme lives in `Styles/MultiComboBox.axaml` and uses a shared maximum width cap so selected tags do not stretch the control indefinitely; override locally only when a page really needs a wider selection box. diff --git a/SecRandom.Core/Abstraction/IAppHost.cs b/SecRandom.Core/Abstraction/IAppHost.cs index 67c1dea52..1f4b49452 100644 --- a/SecRandom.Core/Abstraction/IAppHost.cs +++ b/SecRandom.Core/Abstraction/IAppHost.cs @@ -1,4 +1,4 @@ -using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Hosting; namespace SecRandom.Core.Abstraction; @@ -33,6 +33,16 @@ public static T GetService() /// 如果获取成功,则返回获取到的服务,否则返回null public static T? TryGetService() { - return (T?)Host?.Services.GetService(typeof(T)); + try + { + return (T?)Host?.Services.GetService(typeof(T)); + } + catch (ObjectDisposedException) + { + // 停机流程会先释放服务容器、再清空 Host:这段窗口里解析服务会抛 ObjectDisposedException。 + // 崩溃处理路径本身也要取服务保存配置,因此这里必须按“服务不可用”处理, + // 否则一次停机期的取服务会把异常处理再次打崩。 + return default; + } } } \ No newline at end of file diff --git a/SecRandom.Core/Abstraction/Services/IDrawCommitService.cs b/SecRandom.Core/Abstraction/Services/IDrawCommitService.cs index e27aea19b..484a71bcf 100644 --- a/SecRandom.Core/Abstraction/Services/IDrawCommitService.cs +++ b/SecRandom.Core/Abstraction/Services/IDrawCommitService.cs @@ -6,6 +6,14 @@ namespace SecRandom.Core.Abstraction.Services; /// One logical student draw to persist: temporary records first, then history, all under a single DrawRoundId. /// DrawMethod carries the channel's draw type ((int)DrawType for student channels). /// +/// +/// is the group the draw read its weights from, and is +/// whenever the caller is not scoped to one group (feature off, selector hidden). +/// is the group marker the new records are written into and is never +/// : a channel whose draw was not group-scoped still stamps its own configured default +/// group, so the channels and modes can never collapse into one bucket. When it is the +/// coordinator falls back to (byte-compatible with every pre-existing caller). +/// public sealed record StudentDrawCommit( IReadOnlyList Winners, DateTime DrawTime, @@ -17,7 +25,8 @@ public sealed record StudentDrawCommit( IReadOnlyDictionary? Weights = null, string CourseName = "", string? DrawRoundId = null, - string? HistoryGroup = null); + string? HistoryGroup = null, + string? RecordGroup = null); /// /// One logical lottery draw. Prizes and their assigned students share a single DrawRoundId so history @@ -37,7 +46,9 @@ public sealed record LotteryDrawCommit( int StudentDrawMethod = 0, string CourseName = "", string? DrawRoundId = null, - string? HistoryGroup = null); + string? HistoryGroup = null, + string? RecordGroup = null, + string? StudentRecordGroup = null); /// /// One logical "no roster" number-range draw. Number tickets are synthetic, so the commit writes temporary diff --git a/SecRandom.Core/Abstraction/Services/IProfileCatalogManager.cs b/SecRandom.Core/Abstraction/Services/IProfileCatalogManager.cs index ac8ab3a78..8a06e2002 100644 --- a/SecRandom.Core/Abstraction/Services/IProfileCatalogManager.cs +++ b/SecRandom.Core/Abstraction/Services/IProfileCatalogManager.cs @@ -60,13 +60,24 @@ public interface IProfileCatalogManager bool ClearPrizeHistory(string name); /// - /// Moves the named history records into the target record group ("移到另一组"). Only the + /// Moves the named members' history records into the target record group ("移到另一组"). Only the /// HistoryGroup marker changes: no new record is appended, no DrawRoundId is created, weights and - /// counters are untouched. Empty target means the default group. Returns how many records were - /// moved; throws when the history file is missing or the save fails. + /// counters are untouched. Empty target means the default group. + /// narrows the move to the records currently in that group ( moves every + /// record of the named members, an empty string the default group only), which is what a view + /// filtered to one group shows. Returns how many records were moved; throws when the history file + /// is missing or the save fails. /// - int MoveStudentHistoryGroup(string profileName, IReadOnlyCollection recordIds, string targetGroup); + int MoveStudentHistoryGroup( + string profileName, + IReadOnlyCollection recordIds, + string targetGroup, + string? sourceGroup = null); /// - int MovePrizeHistoryGroup(string profileName, IReadOnlyCollection recordIds, string targetGroup); + int MovePrizeHistoryGroup( + string profileName, + IReadOnlyCollection recordIds, + string targetGroup, + string? sourceGroup = null); } diff --git a/SecRandom.Core/Controls/AnchorGridDropDown.axaml b/SecRandom.Core/Controls/AnchorGridDropDown.axaml new file mode 100644 index 000000000..4e9a66ff1 --- /dev/null +++ b/SecRandom.Core/Controls/AnchorGridDropDown.axaml @@ -0,0 +1,55 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/SecRandom.Core/Controls/AnchorGridDropDown.cs b/SecRandom.Core/Controls/AnchorGridDropDown.cs new file mode 100644 index 000000000..b6e28f298 --- /dev/null +++ b/SecRandom.Core/Controls/AnchorGridDropDown.cs @@ -0,0 +1,124 @@ +using System; +using System.Collections.Generic; +using Avalonia; +using Avalonia.Automation; +using Avalonia.Controls; +using Avalonia.Controls.Primitives; +using Avalonia.Data; +using Avalonia.Layout; +using Avalonia.Media; +using Avalonia.Threading; +using SecRandom.Core.Models.SubConfigs; + +namespace SecRandom.Core.Controls; + +/// +/// 位置下拉框:收起时是一行当前位置的名称(和原来的下拉框文案完全一致), +/// 点开之后展开的是 的 3×3 圆点九宫格。 +/// +/// +/// +/// 收起的部分看起来就是一个下拉框:左边是 里与当前值同序的文本, +/// 右边是下拉箭头,点击(或键盘回车/空格)由 自己的 Flyout 展开。 +/// 展开后点中一格即写回 并收起弹层;用方向键浏览九宫格时弹层保持展开, +/// 所以“看位置”和“选位置”两步不会被键盘打断。 +/// +/// +/// 控件只负责把值、文案、九宫格串起来,格子外观与位置语义分别在 +/// Controls/AnchorGridPicker.axaml 和 里, +/// 下拉框自身的外观在 Controls/AnchorGridDropDown.axaml 里。 +/// +/// +public sealed class AnchorGridDropDown : Button +{ + /// 当前选中的持久化位置值(九宫格外的值会被收敛成中心)。 + public static readonly StyledProperty SelectedValueProperty = + AvaloniaProperty.Register( + nameof(SelectedValue), + (int)NotificationWindowPosition.Center, + defaultBindingMode: BindingMode.TwoWay); + + /// + /// 九格各自的文本,顺序与 一致: + /// 收起状态显示当前值对应的那一条,九宫格里的每一格拿它当提示与无障碍名称。 + /// + public static readonly StyledProperty?> LabelsProperty = + AvaloniaProperty.Register?>(nameof(Labels)); + + private readonly TextBlock _valueText = new() + { + VerticalAlignment = VerticalAlignment.Center, + TextTrimming = TextTrimming.CharacterEllipsis + }; + + private readonly AnchorGridPicker _picker = new(); + private readonly Flyout _flyout; + + static AnchorGridDropDown() + { + SelectedValueProperty.Changed.AddClassHandler( + static (dropdown, _) => dropdown.SyncSelection()); + LabelsProperty.Changed.AddClassHandler( + static (dropdown, _) => dropdown.SyncSelection()); + } + + public AnchorGridDropDown() + { + Content = _valueText; + _picker.SelectionCommitted += OnPickerSelectionCommitted; + + _flyout = new Flyout + { + Placement = PlacementMode.BottomEdgeAlignedRight, + Content = new Border + { + Padding = new Thickness(12), + Child = _picker + } + }; + // 弹层展开后把焦点放到当前格子上,键盘用户从“现在在哪”开始移动, + // 而不是从左上角重新走一遍。Post 到 Input 优先级是为了赢过 Flyout 自己的首次聚焦。 + _flyout.Opened += (_, _) => + Dispatcher.UIThread.Post(_picker.FocusSelectedCell, DispatcherPriority.Input); + Flyout = _flyout; + + SyncSelection(); + } + + public int SelectedValue + { + get => GetValue(SelectedValueProperty); + set => SetValue(SelectedValueProperty, value); + } + + public IReadOnlyList? Labels + { + get => GetValue(LabelsProperty); + set => SetValue(LabelsProperty, value); + } + + private string LabelFor(NotificationWindowPosition value) + { + var labels = Labels; + var index = NotificationWindowAnchorLayout.ToCellIndex((int)value); + return labels is not null && index < labels.Count ? labels[index] : string.Empty; + } + + /// 把值归一化后同时落到收起文案、无障碍名称和九宫格的选中格上。 + private void SyncSelection() + { + var value = NotificationWindowAnchorLayout.Normalize(SelectedValue); + var label = LabelFor(value); + if (_valueText.Text != label) + _valueText.Text = label; + AutomationProperties.SetName(this, label); + if (_picker.SelectedValue != (int)value) + _picker.SelectedValue = (int)value; + } + + private void OnPickerSelectionCommitted(object? sender, EventArgs e) + { + SelectedValue = _picker.SelectedValue; + _flyout.Hide(); + } +} \ No newline at end of file diff --git a/SecRandom.Core/Controls/AnchorGridPicker.axaml b/SecRandom.Core/Controls/AnchorGridPicker.axaml new file mode 100644 index 000000000..cdae79bc5 --- /dev/null +++ b/SecRandom.Core/Controls/AnchorGridPicker.axaml @@ -0,0 +1,64 @@ + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/SecRandom.Core/Controls/AnchorGridPicker.cs b/SecRandom.Core/Controls/AnchorGridPicker.cs new file mode 100644 index 000000000..045e8c34f --- /dev/null +++ b/SecRandom.Core/Controls/AnchorGridPicker.cs @@ -0,0 +1,229 @@ +using System; +using System.Collections.Generic; +using Avalonia; +using Avalonia.Automation; +using Avalonia.Controls; +using Avalonia.Controls.Primitives; +using Avalonia.Data; +using Avalonia.Input; +using Avalonia.Interactivity; +using Avalonia.Layout; +using Avalonia.Media; +using SecRandom.Core.Models.SubConfigs; + +namespace SecRandom.Core.Controls; + +/// +/// 点圆点选位置:3×3 九宫格锚点选择器,点哪一格就选中哪一格对应的浮窗位置。 +/// +/// +/// +/// 九宫格的排列与持久化数值的对应关系由 给出, +/// 和 App 的窗口定位共用同一份映射:左上 → 上 → 右上 → 左 → 中心 → 右 → 左下 → 下 → 右下。 +/// 旧配置里 0–4 的取值(中心 / 顶 / 底 / 左 / 右)逐字节不变,四角是追加值, +/// 所以换成圆点选择器不会让任何人已经保存的位置跳到别的格子上。 +/// +/// +/// 每一格都是真正的 :Tab 能进来、方向键在九宫格里移动、回车/空格确认, +/// 圆点按 里相同顺序的文本显示提示并作为无障碍名称。外观(圆点大小、 +/// 悬停与选中配色、键盘焦点环)全部在 Controls/AnchorGridPicker.axaml 里, +/// 控件本身只负责格子的构造与选中状态。 +/// +/// +public sealed class AnchorGridPicker : UniformGrid +{ + /// 当前选中的持久化位置值(九宫格外的值会被收敛成中心)。 + public static readonly StyledProperty SelectedValueProperty = + AvaloniaProperty.Register( + nameof(SelectedValue), + (int)NotificationWindowPosition.Center, + defaultBindingMode: BindingMode.TwoWay); + + /// + /// 九格各自的提示文本,顺序与 一致;可以留空。 + /// + public static readonly StyledProperty?> LabelsProperty = + AvaloniaProperty.Register?>(nameof(Labels)); + + /// 圆点直径(DIP)。 + public static readonly StyledProperty DotSizeProperty = + AvaloniaProperty.Register(nameof(DotSize), 22d); + + /// 单格点击区域边长(DIP),必须不小于 。 + public static readonly StyledProperty CellSizeProperty = + AvaloniaProperty.Register(nameof(CellSize), 44d); + + /// + /// 用户真正点中(或回车/空格确认)了一格时触发。方向键移动选中不触发, + /// 所以外层下拉框可以据此收起弹出层,而键盘浏览九宫格时弹层保持展开。 + /// + public event EventHandler? SelectionCommitted; + + private const int ColumnCount = 3; + private const string CellClass = "anchor-cell"; + private const string DotClass = "anchor-dot"; + private const string SelectedClass = "selected"; + private const double CellSpacing = 4; + + private readonly List _cells = []; + + static AnchorGridPicker() + { + SelectedValueProperty.Changed.AddClassHandler(static (picker, args) => + { + // 绑定写进来的越界值不会真的显示到界面上:先收敛再重算选中格。 + if (args.NewValue is int value && !NotificationWindowAnchorLayout.IsDefined(value)) + picker.SelectedValue = (int)NotificationWindowAnchorLayout.Normalize(value); + + picker.RefreshSelection(); + }); + LabelsProperty.Changed.AddClassHandler(static (picker, _) => picker.RefreshLabels()); + DotSizeProperty.Changed.AddClassHandler(static (picker, _) => picker.RefreshMetrics()); + CellSizeProperty.Changed.AddClassHandler(static (picker, _) => picker.RefreshMetrics()); + } + + public AnchorGridPicker() + { + Columns = ColumnCount; + Rows = ColumnCount; + ColumnSpacing = CellSpacing; + RowSpacing = CellSpacing; + BuildCells(); + AddHandler(KeyDownEvent, OnPickerKeyDown, RoutingStrategies.Bubble); + } + + public int SelectedValue + { + get => GetValue(SelectedValueProperty); + set => SetValue(SelectedValueProperty, value); + } + + public IReadOnlyList? Labels + { + get => GetValue(LabelsProperty); + set => SetValue(LabelsProperty, value); + } + + public double DotSize + { + get => GetValue(DotSizeProperty); + set => SetValue(DotSizeProperty, value); + } + + public double CellSize + { + get => GetValue(CellSizeProperty); + set => SetValue(CellSizeProperty, value); + } + + private void BuildCells() + { + Children.Clear(); + _cells.Clear(); + + foreach (var value in NotificationWindowAnchorLayout.GridOrder) + { + var dot = new Border(); + dot.Classes.Add(DotClass); + + var cell = new Button + { + Content = dot, + HorizontalContentAlignment = HorizontalAlignment.Center, + VerticalContentAlignment = VerticalAlignment.Center, + Background = Brushes.Transparent, + Padding = default, + MinWidth = 0, + MinHeight = 0, + Cursor = new Cursor(StandardCursorType.Hand) + }; + cell.Classes.Add(CellClass); + cell.Click += (_, _) => + { + SelectedValue = (int)value; + SelectionCommitted?.Invoke(this, EventArgs.Empty); + }; + + _cells.Add(new AnchorGridCell(cell, dot, value)); + Children.Add(cell); + } + + RefreshMetrics(); + RefreshLabels(); + RefreshSelection(); + } + + private void RefreshMetrics() + { + var dotSize = Math.Max(6, DotSize); + var cellSize = Math.Max(dotSize, CellSize); + var radius = new CornerRadius(dotSize / 2); + + foreach (var cell in _cells) + { + cell.Button.Width = cellSize; + cell.Button.Height = cellSize; + cell.Dot.Width = dotSize; + cell.Dot.Height = dotSize; + cell.Dot.CornerRadius = radius; + } + } + + private void RefreshLabels() + { + var labels = Labels; + for (var index = 0; index < _cells.Count; index++) + { + var label = labels is not null && index < labels.Count ? labels[index] : string.Empty; + var button = _cells[index].Button; + ToolTip.SetTip(button, string.IsNullOrWhiteSpace(label) ? null : label); + AutomationProperties.SetName(button, label); + } + } + + private void RefreshSelection() + { + var selected = NotificationWindowAnchorLayout.Normalize(SelectedValue); + foreach (var cell in _cells) + cell.Button.Classes.Set(SelectedClass, cell.Value == selected); + } + + /// 方向键在九宫格里移动并顺带选中;回车/空格由每格自己的按钮处理。 + private void OnPickerKeyDown(object? sender, KeyEventArgs e) + { + var index = _cells.FindIndex(cell => cell.Button.IsFocused); + if (index < 0) + return; + + var (rowDelta, columnDelta) = e.Key switch + { + Key.Left => (0, -1), + Key.Right => (0, 1), + Key.Up => (-1, 0), + Key.Down => (1, 0), + _ => (0, 0) + }; + if (rowDelta == 0 && columnDelta == 0) + return; + + var row = Math.Clamp((index / ColumnCount) + rowDelta, 0, ColumnCount - 1); + var column = Math.Clamp((index % ColumnCount) + columnDelta, 0, ColumnCount - 1); + var target = _cells[(row * ColumnCount) + column]; + SelectedValue = (int)target.Value; + target.Button.Focus(); + e.Handled = true; + } + + /// + /// 把键盘焦点放到当前选中的格子上,供弹出层展开时继承选择: + /// 键盘用户打开下拉框后直接落在“现在的位置”上,方向键从这里继续移动。 + /// + public void FocusSelectedCell() + { + var index = NotificationWindowAnchorLayout.ToCellIndex(SelectedValue); + if (index >= 0 && index < _cells.Count) + _cells[index].Button.Focus(); + } + + private sealed record AnchorGridCell(Button Button, Border Dot, NotificationWindowPosition Value); +} \ No newline at end of file diff --git a/SecRandom.Core/Controls/BorderedProgressRing.cs b/SecRandom.Core/Controls/BorderedProgressRing.cs new file mode 100644 index 000000000..f4ec87eb6 --- /dev/null +++ b/SecRandom.Core/Controls/BorderedProgressRing.cs @@ -0,0 +1,206 @@ +using Avalonia; +using Avalonia.Controls; +using Avalonia.Media; +using SecRandom.Core.Services.FloatingWindow; + +namespace SecRandom.Core.Controls; + +/// +/// 贴着控件四周画的圆角矩形进度环:轨迹是控件轮廓,进度沿轮廓从 +/// 推进并逐渐过渡到 。 +/// +/// +/// +/// 悬浮窗的闪抽按钮是方角控件,需求要求"贴在那个方形的边缘,不要圆形",所以这里不做圆弧环, +/// 而是把圆角矩形轮廓按弧长等分成 段逐段上色:头部永远是最新的颜色、 +/// 起点永远是最初的颜色,整圈填满时才呈现完整渐变。等分点里既有四条直边也有四个圆角, +/// 因此进度看起来是沿控件边缘匀速走的,而不会在转角处突然加速。 +/// +/// +/// 两个端点色由宿主传入而不是写死:窗口把它设成当前主题强调色的一组深浅,进度环就跟着主题走。 +/// +/// +public sealed class BorderedProgressRing : Control +{ + public static readonly StyledProperty ProgressProperty = + AvaloniaProperty.Register(nameof(Progress)); + + /// 控件轮廓的圆角半径(DIP)。0 就是直角矩形。 + public static readonly StyledProperty CornerRadiusProperty = + AvaloniaProperty.Register(nameof(CornerRadius), 8d); + + public static readonly StyledProperty StrokeThicknessProperty = + AvaloniaProperty.Register(nameof(StrokeThickness), 3d); + + /// 未完成部分的底色。为 null 时不画轨迹,只画进度。 + public static readonly StyledProperty TrackBrushProperty = + AvaloniaProperty.Register(nameof(TrackBrush)); + + /// 进度起点颜色(默认是闪抽长按的初始蓝)。 + public static readonly StyledProperty StartColorProperty = + AvaloniaProperty.Register( + nameof(StartColor), + QuickDrawLongPressGesture.RingStartColor); + + /// 进度头部颜色(默认是闪抽长按的完成绿)。 + public static readonly StyledProperty EndColorProperty = + AvaloniaProperty.Register( + nameof(EndColor), + QuickDrawLongPressGesture.RingEndColor); + + private const int SegmentCount = 64; + + static BorderedProgressRing() + { + AffectsRender( + ProgressProperty, + CornerRadiusProperty, + StrokeThicknessProperty, + TrackBrushProperty, + StartColorProperty, + EndColorProperty); + } + + /// 完成比例,0 到 1。 + public double Progress + { + get => GetValue(ProgressProperty); + set => SetValue(ProgressProperty, value); + } + + public double CornerRadius + { + get => GetValue(CornerRadiusProperty); + set => SetValue(CornerRadiusProperty, value); + } + + public double StrokeThickness + { + get => GetValue(StrokeThicknessProperty); + set => SetValue(StrokeThicknessProperty, value); + } + + public IBrush? TrackBrush + { + get => GetValue(TrackBrushProperty); + set => SetValue(TrackBrushProperty, value); + } + + /// 进度起点颜色。 + public Color StartColor + { + get => GetValue(StartColorProperty); + set => SetValue(StartColorProperty, value); + } + + /// 进度头部颜色。 + public Color EndColor + { + get => GetValue(EndColorProperty); + set => SetValue(EndColorProperty, value); + } + + public override void Render(DrawingContext context) + { + var width = Bounds.Width; + var height = Bounds.Height; + if (width <= 0 || height <= 0) + return; + + var thickness = Math.Max(1, StrokeThickness); + var inset = (thickness / 2) + 0.5; + var rect = new Rect(inset, inset, width - (inset * 2), height - (inset * 2)); + if (rect.Width <= 0 || rect.Height <= 0) + return; + + var radius = Math.Clamp(CornerRadius, 0, Math.Min(rect.Width, rect.Height) / 2); + var points = new Point[SegmentCount + 1]; + for (var index = 0; index <= SegmentCount; index++) + points[index] = ResolvePoint(index / (double)SegmentCount, rect, radius); + + if (TrackBrush is { } trackBrush) + { + var trackPen = new Pen(trackBrush, thickness, lineCap: PenLineCap.Round, lineJoin: PenLineJoin.Round); + for (var index = 0; index < SegmentCount; index++) + context.DrawLine(trackPen, points[index], points[index + 1]); + } + + var progress = Math.Clamp(Progress, 0, 1); + if (progress <= 0) + return; + + var filled = Math.Max(1, (int)Math.Round(progress * SegmentCount)); + var startColor = StartColor; + var endColor = EndColor; + for (var index = 0; index < filled; index++) + { + var color = QuickDrawLongPressGesture.LerpColor(startColor, endColor, (index + 0.5) / filled); + var brush = new SolidColorBrush(color); + var pen = new Pen(brush, thickness, lineCap: PenLineCap.Round, lineJoin: PenLineJoin.Round); + context.DrawLine(pen, points[index], points[index + 1]); + } + } + + /// 沿圆角矩形轮廓(顺时针,从左上角之后的顶边起点算)取弧长比例处的点。 + private static Point ResolvePoint(double fraction, Rect rect, double radius) + { + var clamped = Math.Clamp(fraction, 0, 1); + if (radius <= 0.5) + { + var plainLength = 2 * (rect.Width + rect.Height); + var plainDistance = clamped * plainLength; + if (plainDistance <= rect.Width) + return new Point(rect.X + plainDistance, rect.Y); + plainDistance -= rect.Width; + if (plainDistance <= rect.Height) + return new Point(rect.Right, rect.Y + plainDistance); + plainDistance -= rect.Height; + if (plainDistance <= rect.Width) + return new Point(rect.Right - plainDistance, rect.Bottom); + + plainDistance -= rect.Width; + return new Point(rect.X, rect.Bottom - plainDistance); + } + + var straightWidth = rect.Width - (radius * 2); + var straightHeight = rect.Height - (radius * 2); + var quarterArc = Math.PI * radius / 2; + var total = (2 * (straightWidth + straightHeight)) + (4 * quarterArc); + var distance = clamped * total; + + if (distance <= straightWidth) + return new Point(rect.X + radius + distance, rect.Y); + distance -= straightWidth; + + if (distance <= quarterArc) + return OnArc(rect.Right - radius, rect.Y + radius, -Math.PI / 2 + (distance / radius), radius); + distance -= quarterArc; + + if (distance <= straightHeight) + return new Point(rect.Right, rect.Y + radius + distance); + distance -= straightHeight; + + if (distance <= quarterArc) + return OnArc(rect.Right - radius, rect.Bottom - radius, distance / radius, radius); + distance -= quarterArc; + + if (distance <= straightWidth) + return new Point(rect.Right - radius - distance, rect.Bottom); + distance -= straightWidth; + + if (distance <= quarterArc) + return OnArc(rect.X + radius, rect.Bottom - radius, (Math.PI / 2) + (distance / radius), radius); + distance -= quarterArc; + + if (distance <= straightHeight) + return new Point(rect.X, rect.Bottom - radius - distance); + distance -= straightHeight; + + return OnArc(rect.X + radius, rect.Y + radius, Math.PI + (distance / radius), radius); + } + + private static Point OnArc(double centerX, double centerY, double angle, double radius) + { + return new Point(centerX + (radius * Math.Cos(angle)), centerY + (radius * Math.Sin(angle))); + } +} \ No newline at end of file diff --git a/SecRandom.Core/Controls/EdgeCountdownRing.cs b/SecRandom.Core/Controls/EdgeCountdownRing.cs new file mode 100644 index 000000000..5c7650b7b --- /dev/null +++ b/SecRandom.Core/Controls/EdgeCountdownRing.cs @@ -0,0 +1,249 @@ +using System; +using System.Collections.Generic; +using Avalonia; +using Avalonia.Controls; +using Avalonia.Media; +using Avalonia.Media.Immutable; +using SecRandom.Core.Models.SubConfigs; + +namespace SecRandom.Core.Controls; + +/// +/// 内置通知浮窗的四周倒计时环。 +/// +/// +/// 一整条 6px 圆角描边,起点与悬浮窗长按闪抽的进度环相同:左上角之后的顶边上,顺时针推进。 +/// 剩余长度 = 进度 × 周长,缺口从起点顺时针扩大,所以读到的是「边框还剩多少」, +/// 而不是四条各自收缩的碎条。描边颜色按窗口横向铺开(左端 = 第一个色标、右端 = 最后一个), +/// 缺口处留一圈很淡的底槽,避免看起来像断线。控件只负责画,计时与取色都由宿主页面驱动。 +/// +public sealed class EdgeCountdownRing : Control +{ + /// 描边粗细,与全屏通知渠道的四边进度条一致。 + private const double Thickness = 6; + + /// 与浮窗 RootBorder 的 8px 圆角配套、略收一点以贴合边框内侧。 + private const double CornerRadius = 9; + + /// 采样段长度:再短只会增加绘制开销,再长会让环形看起来有棱角。 + private const double SegmentLength = 3; + + private Color _startColor = NotificationCountdownPalette.DefaultStart; + private Color _endColor = NotificationCountdownPalette.DefaultEnd; + private bool _gradient = true; + private double _progress = 1; + + private Size _builtSize; + private double _builtRadius; + private Point[] _points = []; + private IBrush? _trackBrush; + + /// 1 = 整圈完整,0 = 完全消失。 + public double Progress + { + get => _progress; + set + { + var clamped = Math.Clamp(value, 0, 1); + if (Math.Abs(clamped - _progress) < 0.0005) + return; + + _progress = clamped; + InvalidateVisual(); + } + } + + /// + /// 重建描边颜色:只有起始色与终止色两种,渐变时两者之间线性过渡,纯色时传入同一颜色。 + /// + public void SetPalette(bool gradient, Color start, Color end) + { + _gradient = gradient; + _startColor = NotificationCountdownPalette.ToOpaque(start); + _endColor = NotificationCountdownPalette.ToOpaque(end); + + // 尺寸没变也要重建:颜色只缓存一次,绘制时不再逐帧分配画刷。 + _builtSize = default; + InvalidateVisual(); + } + + public override void Render(DrawingContext context) + { + var size = Bounds.Size; + if (size.Width <= 0 || size.Height <= 0) + return; + + var thickness = Math.Min(Thickness, Math.Min(size.Width, size.Height) / 4); + var radius = Math.Min(CornerRadius, Math.Min(size.Width, size.Height) / 4); + EnsureBuilt(size, thickness, radius); + + var count = _points.Length - 1; + if (count <= 0) + return; + + // 底槽:整圈低对比度,缺口处仍能看出边框位置,读作进度而不是断线。 + if (_trackBrush is not null) + { + var trackPen = new Pen(_trackBrush, thickness); + context.DrawRectangle( + null, + trackPen, + new Rect(size).Deflate(thickness / 2), + radius, + radius); + } + + var visible = Math.Clamp(_progress, 0, 1); + var tail = (1 - visible) * count; // 缺口长度(段数),缺口从起点顺时针扩大 + if (visible <= 0) + return; + + // 颜色跟着「过去了多少时间」走:整圈同一时刻是一种颜色,从起始色平滑过渡到终止色。 + // 满圈时是起始色(蓝),时间走完时是终止色(红);不是把蓝和红同时铺在左右两端。 + var elapsed = 1 - visible; + var color = _gradient + ? NotificationCountdownPalette.Sample(_startColor, _endColor, elapsed) + : _startColor; + var pen = new ImmutablePen( + new ImmutableSolidColorBrush(Color.FromArgb(235, color.R, color.G, color.B)), + thickness, + null, + PenLineCap.Round); + + // 只画剩余的那一段尾环:起点固定在左上角之后的顶边上,随时间顺时针被吃掉, + // 与悬浮窗长按闪抽的 BorderedProgressRing(同一处起点、同样顺时针)方向一致。 + for (var i = 0; i < count; i++) + { + var segmentStart = Math.Max(i, tail); + var segmentEnd = Math.Min(i + 1, count); + if (segmentEnd - segmentStart <= 0.0001) + continue; + + var from = segmentStart <= i ? _points[i] : Lerp(_points[i], _points[i + 1], segmentStart - i); + var to = segmentEnd >= i + 1 ? _points[i + 1] : Lerp(_points[i], _points[i + 1], segmentEnd - i); + context.DrawLine(pen, from, to); + } + } + + private void EnsureBuilt(Size size, double thickness, double radius) + { + if (_builtSize == size && Math.Abs(_builtRadius - radius) < 0.01 && _points.Length > 0) + return; + + _builtSize = size; + _builtRadius = radius; + + var rect = new Rect(size).Deflate(thickness / 2); + var pieces = BuildPieces(rect, radius); + + var perimeter = 0.0; + foreach (var piece in pieces) + perimeter += piece.Length; + + if (perimeter <= 0) + { + _points = []; + _trackBrush = null; + return; + } + + var count = Math.Clamp((int)Math.Round(perimeter / SegmentLength), 32, 480); + var points = new Point[count + 1]; + for (var i = 0; i <= count; i++) + points[i] = PointAt(pieces, i * perimeter / count); + + _points = points; + _trackBrush = new SolidColorBrush(Color.FromArgb(36, 128, 128, 128)); + } + + /// + /// 把圆角矩形拆成顺时针八段,起点与悬浮窗长按进度环()一致: + /// 左上角之后的顶边上。依次是顶边、右上角、右边、右下角、底边、左下角、左边、左上角,正好回到起点。 + /// + private static List BuildPieces(Rect rect, double radius) + { + var r = Math.Max(0, Math.Min(radius, Math.Min(rect.Width, rect.Height) / 2)); + var quarter = Math.PI / 2; + + return + [ + Piece.Line(new Point(rect.Left + r, rect.Top), new Point(rect.Right - r, rect.Top)), + Piece.Arc(new Point(rect.Right - r, rect.Top + r), r, -quarter, quarter), + Piece.Line(new Point(rect.Right, rect.Top + r), new Point(rect.Right, rect.Bottom - r)), + Piece.Arc(new Point(rect.Right - r, rect.Bottom - r), r, 0, quarter), + Piece.Line(new Point(rect.Right - r, rect.Bottom), new Point(rect.Left + r, rect.Bottom)), + Piece.Arc(new Point(rect.Left + r, rect.Bottom - r), r, quarter, quarter), + Piece.Line(new Point(rect.Left, rect.Bottom - r), new Point(rect.Left, rect.Top + r)), + Piece.Arc(new Point(rect.Left + r, rect.Top + r), r, Math.PI, quarter) + ]; + } + + private static Point PointAt(List pieces, double distance) + { + foreach (var piece in pieces) + { + if (distance > piece.Length) + { + distance -= piece.Length; + continue; + } + + var t = piece.Length <= 0 ? 0 : Math.Clamp(distance / piece.Length, 0, 1); + return piece.IsArc + ? new Point( + piece.Center.X + piece.Radius * Math.Cos(piece.StartAngle + piece.Sweep * t), + piece.Center.Y + piece.Radius * Math.Sin(piece.StartAngle + piece.Sweep * t)) + : Lerp(piece.Start, piece.End, t); + } + + return pieces[^1].End; + } + + private static Point Lerp(Point start, Point end, double t) + { + return new Point( + start.X + (end.X - start.X) * t, + start.Y + (end.Y - start.Y) * t); + } + + private readonly record struct Piece( + Point Start, + Point End, + Point Center, + double Radius, + double StartAngle, + double Sweep, + double Length) + { + public bool IsArc => Sweep != 0; + + public static Piece Line(Point start, Point end) + { + return new Piece(start, end, default, 0, 0, 0, Distance(start, end)); + } + + public static Piece Arc(Point center, double radius, double startAngle, double sweep) + { + return new Piece( + default, + ArcEnd(center, radius, startAngle + sweep), + center, + radius, + startAngle, + sweep, + radius * Math.Abs(sweep)); + } + + private static Point ArcEnd(Point center, double radius, double angle) + { + return new Point(center.X + radius * Math.Cos(angle), center.Y + radius * Math.Sin(angle)); + } + + private static double Distance(Point start, Point end) + { + var dx = end.X - start.X; + var dy = end.Y - start.Y; + return Math.Sqrt(dx * dx + dy * dy); + } + } +} \ No newline at end of file diff --git a/SecRandom.Core/Controls/QuickDrawResultGridPanel.cs b/SecRandom.Core/Controls/QuickDrawResultGridPanel.cs new file mode 100644 index 000000000..ab73d389c --- /dev/null +++ b/SecRandom.Core/Controls/QuickDrawResultGridPanel.cs @@ -0,0 +1,164 @@ +using System; +using Avalonia; +using Avalonia.Controls; +using SecRandom.Core.Services.FloatingWindow; + +namespace SecRandom.Core.Controls; + +/// +/// 浮窗结果卡的居中自适应网格:列数按可用宽高选择,行内等宽,末行水平居中。 +/// +/// +/// +/// 列数决策在 里,本面板只负责量测与落位: +/// 先量出所有卡片的自然尺寸,再把同一行的卡片拉伸到该行最高、最宽的单元格, +/// 这样短姓名和长姓名混排时行高与列宽仍然整齐;最后一行卡片少时整行居中。 +/// +/// +/// 为什么需要窗口兜底:窗口是 SizeToContent,ScrollViewer 又会用无限高度 +/// 量测内容,面板拿到的 可能有一边是无穷。此时退回窗口的 +/// / ,再退回当前屏幕工作区, +/// 并预留窗口边框与底部提示占用的空间,否则"按屏幕宽高自适应"会退化成永远单列。 +/// +/// +public sealed class QuickDrawResultGridPanel : Panel +{ + private const double FallbackWidth = 1280; + private const double FallbackHeight = 720; + private const double WindowChromeWidth = 48; + private const double WindowChromeHeight = 96; + + private int _columns; + private double _cellWidth; + private double[] _rowHeights = []; + + protected override Size MeasureOverride(Size availableSize) + { + _columns = 0; + _cellWidth = 0; + _rowHeights = []; + + var children = Children; + if (children.Count == 0) + return default; + + var limits = ResolveAvailableSize(availableSize); + var maxWidth = 0.0; + var maxHeight = 0.0; + foreach (var child in children) + { + child.Measure(new Size(limits.Width, double.PositiveInfinity)); + maxWidth = Math.Max(maxWidth, child.DesiredSize.Width); + maxHeight = Math.Max(maxHeight, child.DesiredSize.Height); + } + + if (maxWidth <= 0 || maxHeight <= 0) + return default; + + var columns = QuickDrawResultGridLayout.ResolveColumns( + children.Count, + limits.Width, + limits.Height, + maxWidth, + maxHeight); + if (columns <= 0) + return default; + + var rows = (children.Count + columns - 1) / columns; + var rowHeights = new double[rows]; + for (var index = 0; index < children.Count; index++) + { + var row = index / columns; + rowHeights[row] = Math.Max(rowHeights[row], children[index].DesiredSize.Height); + } + + _columns = columns; + _cellWidth = maxWidth; + _rowHeights = rowHeights; + + var desiredHeight = 0.0; + foreach (var rowHeight in rowHeights) + desiredHeight += rowHeight; + + return new Size(columns * maxWidth, desiredHeight); + } + + protected override Size ArrangeOverride(Size finalSize) + { + if (Children.Count == 0 || _columns <= 0 || _cellWidth <= 0) + return finalSize; + + // 面板可能被拉伸得比内容宽(ItemsControl 是 Stretch),按面板实际宽度逐行居中; + // 若窗口反而比网格窄,仍以网格宽度计算,避免第一列被推到负坐标上裁掉。 + var arrangeWidth = Math.Max(finalSize.Width, _columns * _cellWidth); + var y = 0.0; + for (var row = 0; row < _rowHeights.Length; row++) + { + var rowHeight = _rowHeights[row]; + var first = row * _columns; + var count = Math.Min(_columns, Children.Count - first); + var x = (arrangeWidth - (count * _cellWidth)) / 2; + + for (var column = 0; column < count; column++) + { + Children[first + column].Arrange(new Rect(x, y, _cellWidth, rowHeight)); + x += _cellWidth; + } + + y += rowHeight; + } + + return finalSize; + } + + /// + /// 把量测约束收敛成有限值;无穷/0 时依次退回窗口上限与屏幕工作区。 + /// + private Size ResolveAvailableSize(Size availableSize) + { + var width = availableSize.Width; + var height = availableSize.Height; + var window = TopLevel.GetTopLevel(this) as Window; + + if (window is not null) + { + // SizeToContent 窗口的"可用宽度"就是内容宽度,拿它选列会形成反馈环: + // 少选一列 → 窗口变窄 → 更倾向少选一列。窗口会随结果卡伸缩, + // 所以决策依据必须是窗口上限/屏幕工作区,而不是当前内容宽度。 + if (window.SizeToContent.HasFlag(SizeToContent.Width) || !IsUsable(width)) + width = ResolveWindowLimit(window, true); + if (window.SizeToContent.HasFlag(SizeToContent.Height) || !IsUsable(height)) + height = ResolveWindowLimit(window, false); + } + + if (!IsUsable(width)) + width = FallbackWidth; + if (!IsUsable(height)) + height = FallbackHeight; + + return new Size(width, height); + } + + private static double ResolveWindowLimit(Window window, bool horizontal) + { + var configured = horizontal ? window.MaxWidth : window.MaxHeight; + if (IsUsable(configured)) + return Math.Max(1, configured - (horizontal ? WindowChromeWidth : WindowChromeHeight)); + + var screen = window.Screens.ScreenFromWindow(window) ?? window.Screens.Primary; + if (screen is null) + return horizontal ? FallbackWidth : FallbackHeight; + + var scale = window.RenderScaling > 0 ? window.RenderScaling : 1; + var workingArea = horizontal ? screen.WorkingArea.Width : screen.WorkingArea.Height; + if (workingArea <= 0) + return horizontal ? FallbackWidth : FallbackHeight; + + return Math.Max(1, (workingArea / scale) - (horizontal ? WindowChromeWidth : WindowChromeHeight)); + } + + private static bool IsUsable(double value) + { + return double.IsFinite(value) && value > 0; + } +} \ No newline at end of file diff --git a/SecRandom.Core/Controls/QuickPickSlider.cs b/SecRandom.Core/Controls/QuickPickSlider.cs new file mode 100644 index 000000000..19ff0a780 --- /dev/null +++ b/SecRandom.Core/Controls/QuickPickSlider.cs @@ -0,0 +1,222 @@ +using System.Collections.Generic; +using Avalonia; +using Avalonia.Controls; +using Avalonia.Layout; +using Avalonia.Media; +using SecRandom.Core.Services.FloatingWindow; + +namespace SecRandom.Core.Controls; + +/// +/// 闪抽长按后的竖向快选滑轨:行序由宿主按浮窗所在侧决定,一侧是 5、4、3、2、1、"退出", +/// 另一侧整列镜像("退出"贴屏幕边缘那一端)。 +/// +/// +/// 这个控件不处理任何指针事件(宿主把它整层设成不参与命中测试):手指按在球上横向、纵向拖动时, +/// 窗口层用 把指针高度换算成人数,再回头调 +/// 点亮对应行。这样做的好处是拖动永远不会被某一行的命中测试打断, +/// 也不会出现"手指滑到行缝里就丢掉选择"的情况。 +/// +/// 选中高光由宿主通过 、、 +/// 和 传入当前主题色: +/// 整列在宿主那里共用一块圆角底衬,行本身保持透明,只有当前指向的那一行亮成一块强调色芯片。 +/// +/// +public sealed class QuickPickSlider : StackPanel +{ + /// 当前指向的人数,0 表示"退出",1..5 表示抽取人数。 + public static readonly StyledProperty SelectedCountProperty = + AvaloniaProperty.Register( + nameof(SelectedCount), + QuickDrawLongPressGesture.DefaultCount); + + /// 自上而下的行序(人数,0 表示"退出")。 + public static readonly StyledProperty> RowCountsProperty = + AvaloniaProperty.Register>( + nameof(RowCounts), + QuickDrawLongPressGesture.ResolveRowCounts(pickerOnLeft: true)); + + /// "退出"那一行的文字,由宿主按当前语言传入。 + public static readonly StyledProperty ExitTextProperty = + AvaloniaProperty.Register(nameof(ExitText), "Exit"); + + public static readonly StyledProperty RowHeightProperty = + AvaloniaProperty.Register(nameof(RowHeight), 44d); + + public static readonly StyledProperty LabelFontSizeProperty = + AvaloniaProperty.Register(nameof(LabelFontSize), 18d); + + /// 未选中行自己的底色;宿主按主题传入,滑轨因此不需要整块底衬。 + public static readonly StyledProperty RowBrushProperty = + AvaloniaProperty.Register(nameof(RowBrush)); + + /// 选中行的填充色,通常由主题强调色生成。 + public static readonly StyledProperty ActiveRowBrushProperty = + AvaloniaProperty.Register(nameof(ActiveRowBrush)); + + /// 选中行的描边色。 + public static readonly StyledProperty ActiveRowBorderBrushProperty = + AvaloniaProperty.Register(nameof(ActiveRowBorderBrush)); + + /// 选中行的外发光,深色主题里靠它把高光从背景里提出来。 + public static readonly StyledProperty ActiveRowShadowProperty = + AvaloniaProperty.Register(nameof(ActiveRowShadow)); + + private const string RowClass = "quick-pick-row"; + private const string LabelClass = "quick-pick-label"; + private const string ActiveClass = "active"; + + private readonly List<(Border Row, TextBlock Label, int Count)> _rows = []; + + static QuickPickSlider() + { + SelectedCountProperty.Changed.AddClassHandler( + static (slider, _) => slider.RefreshSelection()); + RowCountsProperty.Changed.AddClassHandler( + static (slider, _) => slider.RebuildRows()); + RowHeightProperty.Changed.AddClassHandler( + static (slider, _) => slider.RefreshMetrics()); + LabelFontSizeProperty.Changed.AddClassHandler( + static (slider, _) => slider.RefreshMetrics()); + ExitTextProperty.Changed.AddClassHandler( + static (slider, _) => slider.RefreshText()); + RowBrushProperty.Changed.AddClassHandler( + static (slider, _) => slider.RefreshSelection()); + ActiveRowBrushProperty.Changed.AddClassHandler( + static (slider, _) => slider.RefreshSelection()); + ActiveRowBorderBrushProperty.Changed.AddClassHandler( + static (slider, _) => slider.RefreshSelection()); + ActiveRowShadowProperty.Changed.AddClassHandler( + static (slider, _) => slider.RefreshSelection()); + } + + public QuickPickSlider() + { + Orientation = Orientation.Vertical; + Spacing = QuickDrawLongPressGesture.RowSpacing; + RebuildRows(); + } + + public int SelectedCount + { + get => GetValue(SelectedCountProperty); + set => SetValue(SelectedCountProperty, value); + } + + public IReadOnlyList RowCounts + { + get => GetValue(RowCountsProperty); + set => SetValue(RowCountsProperty, value); + } + + public string ExitText + { + get => GetValue(ExitTextProperty); + set => SetValue(ExitTextProperty, value); + } + + public double RowHeight + { + get => GetValue(RowHeightProperty); + set => SetValue(RowHeightProperty, value); + } + + public double LabelFontSize + { + get => GetValue(LabelFontSizeProperty); + set => SetValue(LabelFontSizeProperty, value); + } + + public IBrush? RowBrush + { + get => GetValue(RowBrushProperty); + set => SetValue(RowBrushProperty, value); + } + + public IBrush? ActiveRowBrush + { + get => GetValue(ActiveRowBrushProperty); + set => SetValue(ActiveRowBrushProperty, value); + } + + public IBrush? ActiveRowBorderBrush + { + get => GetValue(ActiveRowBorderBrushProperty); + set => SetValue(ActiveRowBorderBrushProperty, value); + } + + public BoxShadows ActiveRowShadow + { + get => GetValue(ActiveRowShadowProperty); + set => SetValue(ActiveRowShadowProperty, value); + } + + private void RebuildRows() + { + Children.Clear(); + _rows.Clear(); + + var counts = RowCounts; + if (counts is null || counts.Count == 0) + counts = QuickDrawLongPressGesture.ResolveRowCounts(pickerOnLeft: true); + + foreach (var count in counts) + { + var label = new TextBlock + { + HorizontalAlignment = HorizontalAlignment.Center, + VerticalAlignment = VerticalAlignment.Center, + TextAlignment = TextAlignment.Center + }; + label.Classes.Add(LabelClass); + + var row = new Border + { + CornerRadius = new CornerRadius(12), + Child = label + }; + row.Classes.Add(RowClass); + + _rows.Add((row, label, count)); + Children.Add(row); + } + + RefreshMetrics(); + RefreshText(); + RefreshSelection(); + } + + private void RefreshMetrics() + { + var height = Math.Max(24, RowHeight); + var fontSize = Math.Max(10, LabelFontSize); + foreach (var (row, label, _) in _rows) + { + row.Height = height; + label.FontSize = fontSize; + } + } + + private void RefreshText() + { + var exitText = string.IsNullOrWhiteSpace(ExitText) ? "Exit" : ExitText; + foreach (var (_, label, count) in _rows) + label.Text = count <= 0 ? exitText : count.ToString(); + } + + private void RefreshSelection() + { + var selected = SelectedCount; + foreach (var (row, _, count) in _rows) + { + var active = count == selected; + row.Classes.Set(ActiveClass, active); + // 整列由宿主在背后铺一块圆角底衬,所以未选中的行保持"透明、无描边、无阴影", + // 只有当前指向的那一行才浮起来成一块强调色芯片。 + row.Background = active ? ActiveRowBrush : RowBrush; + row.BorderBrush = active ? ActiveRowBorderBrush : null; + row.BorderThickness = active ? new Thickness(1.5) : default; + row.BoxShadow = active ? ActiveRowShadow : default; + } + } +} \ No newline at end of file diff --git a/SecRandom.Core/Enums/Configs/DrawMode.cs b/SecRandom.Core/Enums/Configs/DrawMode.cs index 9d6e1f547..1ed9864dd 100644 --- a/SecRandom.Core/Enums/Configs/DrawMode.cs +++ b/SecRandom.Core/Enums/Configs/DrawMode.cs @@ -1,8 +1,22 @@ -namespace SecRandom.Core.Enums.Configs; +namespace SecRandom.Core.Enums.Configs; public enum DrawMode { Repeat, NoRepeat, - HalfRepeat + HalfRepeat, + + /// + /// The order is arranged before the draw instead of being sampled at draw time. It is a mode of its + /// own rather than a fourth repeat policy: repeat limits, average-gap protection and fair weights are + /// all bypassed because the participant is already decided. + /// + /// + /// The settings pages never list this value among the repeat policies — 编排抽取 sits in the + /// 「抽取方式」 dropdown next to the random and fair algorithms, because it answers "who is drawn" + /// rather than "how are repeated draws handled". Selecting it stores this value (the draw side reads + /// only DrawMode) after saving the previous repeat policy in + /// OverridableDrawSettings.SampledDrawMode; see DrawModeSelection. + /// + Orchestrated } \ No newline at end of file diff --git a/SecRandom.Core/Enums/Configs/DrawModeCatalog.cs b/SecRandom.Core/Enums/Configs/DrawModeCatalog.cs new file mode 100644 index 000000000..243a8feae --- /dev/null +++ b/SecRandom.Core/Enums/Configs/DrawModeCatalog.cs @@ -0,0 +1,74 @@ +namespace SecRandom.Core.Enums.Configs; + +/// +/// The one place that names a for anything outside the app: the anonymous audit +/// payload submitted to fair.sectl.cn (fairness.repeatMode), the proof/verification page that +/// renders it, and the IPC/control-plane projection of the same setting. +/// +/// +/// +/// These strings are wire values, not display text: changing one invalidates every proof that already +/// carries it, and the verifier keeps its own fixed list that must stay byte-identical. They live here so +/// a token cannot be spelled two ways in two call sites, which is what previously made "which mode was +/// this draw" hard to answer across the app and the service. +/// +/// +/// orchestrated is not a repeat policy: the order was arranged before the draw. It therefore gets +/// its own token instead of pretending to be no-repeat — a reader of the proof has to be able to +/// tell that the draw was not sampled, and a verifier has to reject a repeat-limit reading of it. +/// +/// +public static class DrawModeCatalog +{ + public const string Repeat = "repeat"; + public const string NoRepeat = "no-repeat"; + public const string HalfRepeat = "half-repeat"; + public const string Orchestrated = "orchestrated"; + public const string Unknown = "unknown"; + + /// + /// 「抽取方式」下拉里代表编排抽取的那一项。它不是注册的抽样算法(没有权重函数可调), + /// 只是各通道设置页把它和随机抽取、公平抽取摆在同一组时用的固定选项 id, + /// 用户选中它时写的是 而不是 AlgorithmId。 + /// + public const string OrchestratedOptionId = "builtin.orchestrated"; + + /// + /// Every token the audit protocol accepts, in declaration order. The verifier's allow-list mirrors this + /// list exactly; adding a fifth mode means adding it to both sides before a build emits it. + /// + public static IReadOnlyList Tokens { get; } = [Repeat, NoRepeat, HalfRepeat, Orchestrated]; + + /// The audit token for a mode; unknown for an undefined value, never a thrown exception. + public static string ToToken(DrawMode mode) => mode switch + { + DrawMode.Repeat => Repeat, + DrawMode.NoRepeat => NoRepeat, + DrawMode.HalfRepeat => HalfRepeat, + DrawMode.Orchestrated => Orchestrated, + _ => Unknown + }; + + /// Reads a token back. Case-sensitive on purpose: the wire vocabulary is lowercase-only. + public static bool TryParse(string? token, out DrawMode mode) + { + switch (token) + { + case Repeat: + mode = DrawMode.Repeat; + return true; + case NoRepeat: + mode = DrawMode.NoRepeat; + return true; + case HalfRepeat: + mode = DrawMode.HalfRepeat; + return true; + case Orchestrated: + mode = DrawMode.Orchestrated; + return true; + default: + mode = default; + return false; + } + } +} \ No newline at end of file diff --git a/SecRandom.Core/Enums/Configs/FairDrawMode.cs b/SecRandom.Core/Enums/Configs/FairDrawMode.cs new file mode 100644 index 000000000..a4bce4da1 --- /dev/null +++ b/SecRandom.Core/Enums/Configs/FairDrawMode.cs @@ -0,0 +1,24 @@ +namespace SecRandom.Core.Enums.Configs; + +/// +/// How a fair student draw treats candidates that are already ahead of the class average. +/// +/// +/// Both modes read the same per-student draw counts; they differ in whether the average gate is a hard +/// pool filter () or a zero-probability weight inside a full pool +/// (). +/// +public enum FairDrawMode +{ + /// + /// Hard average gate: only students at or below the average draw count stay in the candidate pool, + /// then the fair weights rank that already-narrowed pool. + /// + UniformFirst, + + /// + /// Soft average gate: every enabled student stays in the pool, students above the relaxed average + /// threshold get weight 0 and therefore can never be drawn, and the rest keep graded weights. + /// + RandomFirst +} \ No newline at end of file diff --git a/SecRandom.Core/Enums/Configs/RandomNumberResetBehavior.cs b/SecRandom.Core/Enums/Configs/RandomNumberResetBehavior.cs new file mode 100644 index 000000000..e6fbfaf30 --- /dev/null +++ b/SecRandom.Core/Enums/Configs/RandomNumberResetBehavior.cs @@ -0,0 +1,17 @@ +namespace SecRandom.Core.Enums.Configs; + +/// +/// 随机数抽取页“重置”时处理哪一层数据。 +/// +/// +/// 随机数没有名单历史记录,重置只涉及两样东西:临时剩余数字和随机数统计。名单持久历史属于 +/// 公平抽取的权重来源,绝不能被这个重置动作清掉,因此这里刻意不提供“清除名单历史”的选项。 +/// +public enum RandomNumberResetBehavior +{ + /// 只清临时剩余数字,保留统计;默认值。 + TemporaryOnly = 0, + + /// 清临时剩余数字,同时清掉概览页使用的随机数统计。 + TemporaryAndStatistics = 1 +} \ No newline at end of file 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/MainConfigModel.cs b/SecRandom.Core/Models/MainConfigModel.cs index 00d128505..97a80b6bd 100644 --- a/SecRandom.Core/Models/MainConfigModel.cs +++ b/SecRandom.Core/Models/MainConfigModel.cs @@ -18,6 +18,7 @@ using LotterySettingsConfig = SecRandom.Core.Models.SubConfigs.Picking.LotterySettingsConfig; using OverridableDrawSettings = SecRandom.Core.Models.SubConfigs.Picking.OverridableDrawSettings; using QuickDrawSettingsConfig = SecRandom.Core.Models.SubConfigs.Picking.QuickDrawSettingsConfig; +using RandomNumberSettingsConfig = SecRandom.Core.Models.SubConfigs.Picking.RandomNumberSettingsConfig; using RollCallSettingsConfig = SecRandom.Core.Models.SubConfigs.Picking.RollCallSettingsConfig; namespace SecRandom.Core.Models; @@ -38,6 +39,7 @@ public partial class MainConfigModel : ConfigBase, IJsonOnDeserialized [ObservableProperty] private RollCallSettingsConfig _rollCallSettings = new(); [ObservableProperty] private QuickDrawSettingsConfig _quickDrawSettings = new(); [ObservableProperty] private LotterySettingsConfig _lotterySettings = new(); + [ObservableProperty] private RandomNumberSettingsConfig _randomNumberSettings = new(); [ObservableProperty] private FloatingWindowSettingsConfig _floatingWindowSettings = new(); private NotificationSettingsConfig _notificationSettings = new(); @@ -93,6 +95,10 @@ public MoreSettingsConfig LegacyMoreSettingsOnLoad public LotterySettingsConfig EffectiveLotterySettings => SimpleModeEnabled ? SimpleModeDefaults.LotterySettings : LotterySettings; + [JsonIgnore] + public RandomNumberSettingsConfig EffectiveRandomNumberSettings => + SimpleModeEnabled ? SimpleModeDefaults.RandomNumberSettings : RandomNumberSettings; + [JsonIgnore] public FairDrawSettingsConfig EffectiveFairDrawSettings => SimpleModeEnabled ? SimpleModeDefaults.FairDrawSettings : FairDrawSettings; diff --git a/SecRandom.Core/Models/Orchestration/OrchestrationModels.cs b/SecRandom.Core/Models/Orchestration/OrchestrationModels.cs new file mode 100644 index 000000000..d108c9455 --- /dev/null +++ b/SecRandom.Core/Models/Orchestration/OrchestrationModels.cs @@ -0,0 +1,364 @@ +using System.Text.Json.Serialization; + +namespace SecRandom.Core.Models.Orchestration; + +/// +/// Which built-in draw channel an arranged list belongs to. A roll-call arrangement also serves quick draw, +/// because both channels draw from the same student roster and share its temporary records. +/// +public enum OrchestrationTarget +{ + RollCall = 0, + Lottery = 1 +} + +/// +/// The five rule lists one arranged profile owns. Every list answers a different question, so the profile keeps +/// them apart instead of mixing them into one table: 排斥 = 谁不参加(全局), 权重 = 谁的相对概率更高, +/// 延后 = 谁这一轮先不抽, 顺序 = 这一轮的出场队列, 必中 = 这一轮谁必须排在最前. +/// +public enum OrchestrationRuleKind +{ + Exclude = 0, + Weight = 1, + Defer = 2, + Order = 3, + Guarantee = 4 +} + +/// +/// Which of the five rule lists this profile actually uses. +/// +/// +/// 「顺序」和「必中」回答的是同一个问题——这一轮谁先出场——所以两者在开关层面互斥:打开其中一个就把另一个 +/// 关掉。 是这条互斥的唯一入口,页面和任何调用方都走它,免得两个开关同时亮着而 +/// 运行时只能靠隐藏的优先级裁决。关掉一个规则只停止使用它的数据,不会删除名单内容。 +/// +public sealed class OrchestrationRules +{ + /// 排斥名单:这些人完全不参加本名单的任何一轮。 + public bool Exclude { get; set; } = true; + + /// 权重名单:本轮手动权重作为公平权重的乘数。 + public bool Weight { get; set; } = true; + + /// 延后名单:这些人本轮的抽取往后放(只影响配置的那一轮)。 + public bool Defer { get; set; } = true; + + /// 顺序名单:本轮按队列顺序出场。 + public bool Order { get; set; } = true; + + /// 必中名单:这些人本轮排在最前。与 互斥。 + public bool Guarantee { get; set; } + + public bool IsEnabled(OrchestrationRuleKind kind) => kind switch + { + OrchestrationRuleKind.Exclude => Exclude, + OrchestrationRuleKind.Weight => Weight, + OrchestrationRuleKind.Defer => Defer, + OrchestrationRuleKind.Order => Order, + OrchestrationRuleKind.Guarantee => Guarantee, + _ => false + }; + + /// + /// Turns one rule list on or off. Enabling 顺序 turns 必中 off and the other way round, because a round can + /// only follow one answer to "who comes out first". + /// + public void SetEnabled(OrchestrationRuleKind kind, bool enabled) + { + switch (kind) + { + case OrchestrationRuleKind.Exclude: + Exclude = enabled; + break; + case OrchestrationRuleKind.Weight: + Weight = enabled; + break; + case OrchestrationRuleKind.Defer: + Defer = enabled; + break; + case OrchestrationRuleKind.Order: + Order = enabled; + if (enabled) + Guarantee = false; + break; + case OrchestrationRuleKind.Guarantee: + Guarantee = enabled; + if (enabled) + Order = false; + break; + } + } + + public OrchestrationRules Clone() => new() + { + Exclude = Exclude, + Weight = Weight, + Defer = Defer, + Order = Order, + Guarantee = Guarantee + }; +} + +/// +/// One arranged draw list: a fixed schedule of who comes out, in which round, in which order. +/// +/// +/// The profile is deliberately independent of the roster it draws from ( is a +/// name, not a copy of the list). Members are keyed by so a +/// rename or renumber in the roster never silently re-points a scheduled position at someone else; a member +/// whose record disappeared is only flagged . +/// +public sealed class OrchestrationProfile +{ + public const int MaxRounds = 10; + + /// 2 = 五名单(排斥/权重/延后/顺序/必中);1 是只有排除/延后/定序/权重字段的旧格式。 + public const int CurrentFormatVersion = 2; + + public int FormatVersion { get; set; } = CurrentFormatVersion; + + public string Id { get; set; } = string.Empty; + + public string Name { get; set; } = string.Empty; + + public OrchestrationTarget Target { get; set; } + + public string SourceListName { get; set; } = string.Empty; + + /// Only one profile per (target, source list) is active at a time. + public bool IsActive { get; set; } + + /// How many rounds one cycle has (1..). + public int RoundCount { get; set; } = 1; + + /// Which of the five rule lists this profile uses. + public OrchestrationRules Rules { get; set; } = new(); + + public List Members { get; set; } = []; + + public List Rounds { get; set; } = []; + + [JsonIgnore] + public int EffectiveRoundCount => Math.Clamp(RoundCount, 1, MaxRounds); + + public OrchestrationMember? FindMember(Guid recordId) => + Members.FirstOrDefault(member => member.RecordId == recordId); + + /// + /// Returns the per-round arrangement for , creating it on first use. Rounds are + /// stored sparsely: a round with no order, skips, guarantees, or weights has no row until something is + /// configured. + /// + public OrchestrationRound GetRound(int round) + { + var index = Math.Clamp(round, 1, EffectiveRoundCount); + var existing = Rounds.FirstOrDefault(candidate => candidate.Index == index); + if (existing is not null) + return existing; + + var created = new OrchestrationRound { Index = index }; + Rounds.Add(created); + Rounds.Sort((left, right) => left.Index.CompareTo(right.Index)); + return created; + } + + /// + /// Sets the global exclusion of one member. Excluding clears every trace of that member in every round + /// (a member who never takes part must not stay in a round's queue, skip, guarantee, or weight list), + /// while un-excluding only lifts the flag so no arrangement is silently rewritten. + /// + public void SetExcluded(Guid recordId, bool excluded) + { + var member = FindMember(recordId); + if (member is null) + return; + + member.IsExcluded = excluded; + if (excluded is false) + return; + + foreach (var round in Rounds) + round.RemoveMember(recordId); + } + + /// + /// Postpones one member for one round. Postponing lifts a global exclusion and removes the member from that + /// round's queue and guarantee group, because someone who does not take part cannot also be scheduled. + /// + public void SetSkipped(OrchestrationRound round, Guid recordId, bool skipped) + { + ArgumentNullException.ThrowIfNull(round); + var has = round.Skipped.Contains(recordId); + if (skipped) + { + var member = FindMember(recordId); + if (member is not null) + member.IsExcluded = false; + if (!has) + round.Skipped.Add(recordId); + round.Order.Remove(recordId); + round.Guaranteed.Remove(recordId); + return; + } + + if (has) + round.Skipped.Remove(recordId); + } + + /// Adds or removes one member from the round's 必中 group. 必中 and 顺序 are mutually exclusive. + public void SetGuaranteed(OrchestrationRound round, Guid recordId, bool guaranteed) + { + ArgumentNullException.ThrowIfNull(round); + if (guaranteed) + SetSkipped(round, recordId, false); + + var has = round.Guaranteed.Contains(recordId); + if (guaranteed) + { + if (!has) + round.Guaranteed.Add(recordId); + round.Order.Remove(recordId); + return; + } + + if (has) + round.Guaranteed.Remove(recordId); + } + + /// + /// Writes the round's 顺序 queue. The sequence is the round's lineup: members omitted from it still take + /// part and are filled in by weight behind it, so a partial queue is a preference rather than a filter. + /// + public void SetOrder(OrchestrationRound round, IReadOnlyList sequence) + { + ArgumentNullException.ThrowIfNull(round); + ArgumentNullException.ThrowIfNull(sequence); + var members = Members.Select(member => member.RecordId).ToHashSet(); + round.Order = sequence + .Where(members.Contains) + .Distinct() + .ToList(); + // 顺序与必中互斥:写队列等于说「这一轮按队列走」,必中名单的优先级不再参与。 + foreach (var recordId in round.Order) + round.Guaranteed.Remove(recordId); + } + + /// + /// Sets (or clears) one member's 权重 multiplier for one round. Weight 0 is not an exclusion: it moves the + /// member behind the weighted fill while everyone still takes part. + /// + public void SetWeight(OrchestrationRound round, Guid recordId, double? weight) + { + ArgumentNullException.ThrowIfNull(round); + if (weight is null) + round.Weights.Remove(recordId); + else + round.Weights[recordId] = Math.Clamp(weight.Value, 0d, 100d); + } +} + +/// One scheduled participant; the roster record itself stays in the student list / prize pool. +public sealed class OrchestrationMember +{ + public Guid RecordId { get; set; } + + /// Display snapshot (student number / prize number) so a deleted source record stays readable. + public string Number { get; set; } = string.Empty; + + /// Display snapshot; never used as identity. + public string Name { get; set; } = string.Empty; + + /// Global exclusion: this member never takes part in any round. + public bool IsExcluded { get; set; } + + /// The roster record is gone; the row is kept so the schedule can be repaired by hand. + public bool IsSourceMissing { get; set; } +} + +/// +/// Per-round arrangement: the round's 延后 / 顺序 / 必中 / 权重 lists. Every collection is "what differs from +/// the default", so an untouched round costs nothing: no queue means the weighted fill decides, no skip means +/// everyone takes part, no guarantee means nobody jumps the queue, no weight means the fair weight alone +/// decides. +/// +public sealed class OrchestrationRound +{ + public int Index { get; set; } + + /// + /// The round's 顺序 queue, in draw order. It is a queue, not a set of absolute positions: a member that + /// already drew (or was postponed / excluded) leaves the queue, and everyone behind moves up one place. + /// That is what makes 「第 3 个抽中」 actually mean the third draw of the round instead of the third slot of + /// the current remainder. + /// + /// + /// Members missing from the queue still take part; the weighted fill seats them behind it, so a partial + /// queue is a preference, not a filter. + /// + public List Order { get; set; } = []; + + /// Record ids that sit this round out (延后); they return automatically in the next round. + public List Skipped { get; set; } = []; + + /// + /// Record ids that must come out first this round (必中). The group is ordered by the effective weight, so + /// a weight still decides who of the guaranteed five goes first, and then by the order they were added. + /// Mutually exclusive with at the switch level. + /// + public List Guaranteed { get; set; } = []; + + /// Manual multipliers on the fair weight, keyed by record id. Missing means 1. + public Dictionary Weights { get; set; } = []; + + /// + /// Format-1 「第几个抽中」 pins, kept only so an existing file can be migrated: the store folds them into + /// on read and always writes this property as null. A pin was an absolute slot + /// in the shrinking remainder, which is exactly the bug the queue replaced. + /// + [JsonPropertyName("Pins")] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public List? LegacyPins { get; set; } + + /// Drops every arrangement this round carries for one member. + public void RemoveMember(Guid recordId) + { + Order.Remove(recordId); + Skipped.Remove(recordId); + Guaranteed.Remove(recordId); + Weights.Remove(recordId); + } +} + +/// Format-1 only: a fixed 1-based position inside one round. Migrated into . +public sealed class OrchestrationPin +{ + public Guid RecordId { get; set; } + + public int Position { get; set; } +} + +/// +/// Where the next draw continues: the active round of one profile. Persisted separately from the profile so a +/// draw and a settings edit never race on the same file. +/// +public sealed class OrchestrationRuntime +{ + public string ProfileId { get; set; } = string.Empty; + + public int Round { get; set; } = 1; + + public DateTime UpdatedAt { get; set; } +} + +/// +/// One participant as the ordering algorithm sees it: the already-resolved fair weight (RandomFirst semantics, +/// multiplied by any manual weight) plus the history figures the deferred tail is ordered by. +/// +public readonly record struct OrchestrationCandidate( + Guid RecordId, + double SamplingWeight, + int DrawCount, + DateTime LastDrawn, + bool IsExcluded); \ No newline at end of file diff --git a/SecRandom.Core/Models/SubConfigs/FloatingWindowSettingsConfig.cs b/SecRandom.Core/Models/SubConfigs/FloatingWindowSettingsConfig.cs index 8b0043f0a..8b2cc39c8 100644 --- a/SecRandom.Core/Models/SubConfigs/FloatingWindowSettingsConfig.cs +++ b/SecRandom.Core/Models/SubConfigs/FloatingWindowSettingsConfig.cs @@ -8,7 +8,8 @@ public partial class FloatingWindowSettingsConfig : ObservableObject [ObservableProperty] private bool _startupDisplayFloatingWindow = true; /// - /// 在屏幕左右两侧各显示一扇悬浮窗。开启后两扇窗分别钉在左/右边缘,只能纵向移动。 + /// 在屏幕左右两侧各显示一扇悬浮窗。开启后主窗钉在它原本那一侧、另一侧补一扇副窗, + /// 两扇窗分别钉在各自边缘,只能纵向移动。 /// [ObservableProperty] private bool _showOnBothSides = false; @@ -23,7 +24,7 @@ public partial class FloatingWindowSettingsConfig : ObservableObject [ObservableProperty] private bool _syncBothSidesAnchor = true; /// - /// 右侧副窗的纵向锚点(屏幕坐标里窗口中心 Y)。为 null 时副窗跟随主窗的纵向位置。 + /// 另一侧副窗的纵向锚点(屏幕坐标里窗口中心 Y)。为 null 时副窗跟随主窗的纵向位置。 /// /// /// 用可空整数是为了让"还没记住过"与"记住的是 0"可区分;控制面目录按类型归类, @@ -54,14 +55,26 @@ public partial class FloatingWindowSettingsConfig : ObservableObject [ObservableProperty] private int _stickToEdgeRecoverSeconds = 3; [ObservableProperty] private int _stickToEdgeDisplayStyle = 1; [ObservableProperty] private int _dockedWindowSize = 32; + + // 收纳手柄的“文字”样式:空字符串等于沿用本地化默认文字(中文“抽”、英文“Go”)。 + // 允许的语言与长度由 FloatingWindowDockHandle 决定,非中文语言不限“一个字”。 + [ObservableProperty] private string _stickToEdgeDisplayText = string.Empty; + + // 收纳手柄的“图标”样式:图标字形为空时回退到默认头像图标,要恢复默认就把这个值清空 + [ObservableProperty] private string _stickToEdgeDisplayIconGlyph = string.Empty; + + // 收纳手柄的自定义图片文件名,与 FloatingWindowIconService 管理的 PNG 同名 + [ObservableProperty] private string _stickToEdgeDisplayIconImage = string.Empty; [ObservableProperty] private bool _draggable = true; [ObservableProperty] private int _floatingWindowSize = 56; - // 悬浮窗自定义文字:默认关闭;空字符串等于不显示,旧配置缺字段时按默认值加载 - [ObservableProperty] private bool _enableFloatingWindowText; - [ObservableProperty] private string _floatingWindowText = string.Empty; - // 自定义文字字号(像素):0 表示跟随悬浮窗尺寸自动缩放,与按钮字号保持同一比例 - [ObservableProperty] private int _floatingWindowTextFontSize; [ObservableProperty] private int _longPressDuration = 500; + + /// + /// 闪抽按钮支持长按快选:按住时按钮四周走一圈蓝→绿进度环,按住满 + /// 毫秒后浮窗收起成球、左侧滑出 1–5 人快选滑轨, + /// 松手即按选中的头像开抽。关掉后闪抽按钮回到"点一下抽 1 人"的老行为。 + /// + [ObservableProperty] private bool _enableQuickDrawLongPress = true; [ObservableProperty] private bool _doNotStealFocus = true; [ObservableProperty] private bool _hideOnForeground = false; [ObservableProperty] private string _hideOnForegroundWindowTitles = string.Empty; 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/General/BasicSettingsConfig.cs b/SecRandom.Core/Models/SubConfigs/General/BasicSettingsConfig.cs index 98263c111..8faf57867 100644 --- a/SecRandom.Core/Models/SubConfigs/General/BasicSettingsConfig.cs +++ b/SecRandom.Core/Models/SubConfigs/General/BasicSettingsConfig.cs @@ -1,4 +1,4 @@ -using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.ComponentModel; using SecRandom.Core.Enums.Configs; using System.Text.Json.Serialization; @@ -14,6 +14,13 @@ public partial class BasicSettingsConfig : ObservableObject [ObservableProperty] private bool _backgroundResident = true; [ObservableProperty] private bool _urlProtocol = false; + /// + /// 结构化自动化 IPC(v1 JSON 请求、v2 RPC 与事件管道)的总开关。 + /// 默认开启;关闭只影响结构化通道,ShowMainWindow/Restart/Url: + /// 这类无返回值的旧式生命周期转发仍然保留,因此"第二次启动转到已运行实例"不会被关掉。 + /// + [ObservableProperty] private bool _automationIpcEnabled = true; + // Stored separately from the user-facing switches so a disabled size setting retains its last size. [ObservableProperty] private double _mainWindowWidth = 1200; [ObservableProperty] private double _mainWindowHeight = 800; diff --git a/SecRandom.Core/Models/SubConfigs/NotificationCountdownPalette.cs b/SecRandom.Core/Models/SubConfigs/NotificationCountdownPalette.cs new file mode 100644 index 000000000..fc3a97d1e --- /dev/null +++ b/SecRandom.Core/Models/SubConfigs/NotificationCountdownPalette.cs @@ -0,0 +1,36 @@ +using System; +using Avalonia.Media; + +namespace SecRandom.Core.Models.SubConfigs; + +/// +/// 内置通知浮窗倒计时描边的配色规则。 +/// +/// +/// 倒计时描边只有两种颜色:起始色与终止色(渐变模式下两者之间线性过渡,纯色模式下两者相同)。 +/// 颜色跟着剩余时间走,而不是沿窗口铺开:满圈时整圈都是起始色(蓝),时间走完时整圈都是终止色(红), +/// 中间每一帧都是两者之间的插值,所以读起来是「颜色慢慢变过去」。 +/// 整圈同一时刻只有一种颜色,环上就不会出现终止色撞起始色的接缝。 +/// +public static class NotificationCountdownPalette +{ + public static Color DefaultStart => Color.Parse("#2E8BFF"); + + public static Color DefaultEnd => Color.Parse("#EF4444"); + + /// 描边永远不透明:透明度属于整个浮窗()。 + public static Color ToOpaque(Color color) => Color.FromArgb(255, color.R, color.G, color.B); + + /// position 是窗口横向归一化位置:0 = 左端(起始色),1 = 右端(终止色)。 + public static Color Sample(Color start, Color end, double position) + { + var amount = Math.Clamp(position, 0, 1); + return Lerp(ToOpaque(start), ToOpaque(end), amount); + } + + private static Color Lerp(Color from, Color to, double amount) => Color.FromArgb( + (byte)Math.Round(from.A + (to.A - from.A) * amount), + (byte)Math.Round(from.R + (to.R - from.R) * amount), + (byte)Math.Round(from.G + (to.G - from.G) * amount), + (byte)Math.Round(from.B + (to.B - from.B) * amount)); +} \ No newline at end of file diff --git a/SecRandom.Core/Models/SubConfigs/NotificationSettingsConfig.cs b/SecRandom.Core/Models/SubConfigs/NotificationSettingsConfig.cs index 5ba422648..db409e84e 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; @@ -144,10 +174,20 @@ public partial class NotificationChannelSettings : ObservableObject, IJsonOnDese private bool _hasExplicitEnabled; [ObservableProperty] private bool _animation = true; private string _enabledMonitor = ""; - [ObservableProperty] private int _windowPosition = 0; + private int _windowPosition = (int)NotificationWindowPosition.Center; [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,13 @@ 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 Color _countdownGradientStart = NotificationCountdownPalette.DefaultStart; + private Color _countdownGradientEnd = NotificationCountdownPalette.DefaultEnd; + private List? _legacyCountdownGradientColors; + public bool UseBuiltInOnServiceFailure { get => _useBuiltInOnServiceFailure; @@ -196,6 +243,23 @@ public string EnabledMonitor : value); } + /// + /// 内置通知浮窗的九宫格位置,取值见 。 + /// + /// + /// 越界值(手改配置、旧实验值)收敛成"中心",与旧配置缺这个键时的落位一致; + /// 0–4 的含义保持不变,四角是追加值。 + /// + public int WindowPosition + { + get => _windowPosition; + set => SetProperty( + ref _windowPosition, + NotificationWindowAnchorLayout.IsDefined(value) + ? value + : (int)NotificationWindowPosition.Center); + } + public int NotificationServiceType { get => _notificationServiceType; @@ -224,6 +288,85 @@ 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 Color CountdownGradientStart + { + get => _countdownGradientStart; + set => SetProperty(ref _countdownGradientStart, NotificationCountdownPalette.ToOpaque(value)); + } + + /// 渐变模式的终止色(窗口右端)。 + public Color CountdownGradientEnd + { + get => _countdownGradientEnd; + set => SetProperty(ref _countdownGradientEnd, NotificationCountdownPalette.ToOpaque(value)); + } + + /// + /// 旧版的任意色标列表(2–6 个)。倒计时现在只有起始色与终止色,这个属性只负责把旧配置的 + /// 首尾两色迁移过来,读取恒为 null,所以再保存时不会写回旧键。 + /// + [JsonPropertyName("countdown_gradient_colors")] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public List? LegacyCountdownGradientColors + { + get => null; + set => _legacyCountdownGradientColors = value; + } + + [JsonIgnore] + public bool UsesEdgeCountdown => CountdownStyle == (int)NotificationCountdownStyle.Edge; + + /// 描边实际使用的起始色:纯色模式两个端点同色。 + [JsonIgnore] + public Color ResolvedCountdownStart => + CountdownColorMode == (int)NotificationCountdownColorMode.Solid + ? CountdownSolidColor + : CountdownGradientStart; + + /// 描边实际使用的终止色:纯色模式两个端点同色。 + [JsonIgnore] + public Color ResolvedCountdownEnd => + CountdownColorMode == (int)NotificationCountdownColorMode.Solid + ? CountdownSolidColor + : CountdownGradientEnd; + public bool Enabled { get => _enabled; @@ -260,8 +403,29 @@ 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; + // 旧版把渐变存成 2–6 个色标的列表;现在只剩起止两色,取首尾两色迁移过来。 + if (_legacyCountdownGradientColors is { Count: > 0 } legacyColors) + { + _countdownGradientStart = NotificationCountdownPalette.ToOpaque(legacyColors[0]); + _countdownGradientEnd = NotificationCountdownPalette.ToOpaque(legacyColors[^1]); + } + + _countdownGradientStart = NotificationCountdownPalette.ToOpaque(_countdownGradientStart); + _countdownGradientEnd = NotificationCountdownPalette.ToOpaque(_countdownGradientEnd); + _countdownSolidColor = NotificationCountdownPalette.ToOpaque(_countdownSolidColor); + _legacyAutoCloseTime = null; _legacyUseBuiltInOnClassIslandFailure = null; + _legacyCountdownGradientColors = null; } partial void OnDisplayDurationChanging(int value) => _hasDisplayDuration = true; @@ -295,3 +459,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/Models/SubConfigs/NotificationWindowPosition.cs b/SecRandom.Core/Models/SubConfigs/NotificationWindowPosition.cs new file mode 100644 index 000000000..0b545d5fd --- /dev/null +++ b/SecRandom.Core/Models/SubConfigs/NotificationWindowPosition.cs @@ -0,0 +1,118 @@ +namespace SecRandom.Core.Models.SubConfigs; + +/// +/// 内置通知浮窗在屏幕工作区里的九宫格锚点。 +/// +/// +/// 数值就是 的持久化值,必须逐字节稳定: +/// 0–4 是旧版只有五档时的取值(中心 / 顶部 / 底部 / 左侧 / 右侧),5–8 是后来补上的四角, +/// 只能追加、不能重排,否则旧配置会跑到别的格子上。 +/// +public enum NotificationWindowPosition +{ + /// 屏幕工作区正中间(旧配置缺键时的默认值)。 + Center = 0, + + Top = 1, + + Bottom = 2, + + Left = 3, + + Right = 4, + + TopLeft = 5, + + TopRight = 6, + + BottomLeft = 7, + + BottomRight = 8 +} + +/// 浮窗在水平方向上的落位:贴左、居中还是贴右。 +public enum NotificationWindowHorizontalAnchor +{ + Left, + Center, + Right +} + +/// 浮窗在垂直方向上的落位:贴顶、居中还是贴底。 +public enum NotificationWindowVerticalAnchor +{ + Top, + Center, + Bottom +} + +/// +/// 九宫格锚点的纯计算规则:持久化数值 ↔ 3×3 网格位置 ↔ 水平/垂直落位。 +/// +/// +/// 设置页的圆点选择器与 App 的窗口定位共用这一份映射,两者不会各写一套 switch 而慢慢跑偏。 +/// 这里是纯函数,不依赖 Avalonia 的窗口类型,因此可以直接单元测试。 +/// +public static class NotificationWindowAnchorLayout +{ + /// 九宫格按行优先排列的持久化值:左上 → 上 → 右上 → 左 → 中心 → 右 → 左下 → 下 → 右下。 + public static IReadOnlyList GridOrder { get; } = + [ + NotificationWindowPosition.TopLeft, + NotificationWindowPosition.Top, + NotificationWindowPosition.TopRight, + NotificationWindowPosition.Left, + NotificationWindowPosition.Center, + NotificationWindowPosition.Right, + NotificationWindowPosition.BottomLeft, + NotificationWindowPosition.Bottom, + NotificationWindowPosition.BottomRight + ]; + + /// 九宫格的格子数(3×3)。 + public const int CellCount = 9; + + /// 持久化值是否落在九宫格内。 + public static bool IsDefined(int value) => value is >= 0 and < CellCount; + + /// 把任意整数收敛成合法的九宫格值;越界值按"中心"处理,与旧配置缺键时一致。 + public static NotificationWindowPosition Normalize(int value) => + IsDefined(value) ? (NotificationWindowPosition)value : NotificationWindowPosition.Center; + + /// 持久化值在九宫格里的格子序号(行优先,0 是左上角)。 + public static int ToCellIndex(int value) + { + var normalized = Normalize(value); + for (var index = 0; index < GridOrder.Count; index++) + { + if (GridOrder[index] == normalized) + return index; + } + + return GridOrder.Count / 2; + } + + /// 解析出浮窗贴哪一侧、贴哪一端。 + public static (NotificationWindowHorizontalAnchor Horizontal, NotificationWindowVerticalAnchor Vertical) Resolve( + int value) => + Normalize(value) switch + { + NotificationWindowPosition.Top => (NotificationWindowHorizontalAnchor.Center, + NotificationWindowVerticalAnchor.Top), + NotificationWindowPosition.Bottom => (NotificationWindowHorizontalAnchor.Center, + NotificationWindowVerticalAnchor.Bottom), + NotificationWindowPosition.Left => (NotificationWindowHorizontalAnchor.Left, + NotificationWindowVerticalAnchor.Center), + NotificationWindowPosition.Right => (NotificationWindowHorizontalAnchor.Right, + NotificationWindowVerticalAnchor.Center), + NotificationWindowPosition.TopLeft => (NotificationWindowHorizontalAnchor.Left, + NotificationWindowVerticalAnchor.Top), + NotificationWindowPosition.TopRight => (NotificationWindowHorizontalAnchor.Right, + NotificationWindowVerticalAnchor.Top), + NotificationWindowPosition.BottomLeft => (NotificationWindowHorizontalAnchor.Left, + NotificationWindowVerticalAnchor.Bottom), + NotificationWindowPosition.BottomRight => (NotificationWindowHorizontalAnchor.Right, + NotificationWindowVerticalAnchor.Bottom), + _ => (NotificationWindowHorizontalAnchor.Center, NotificationWindowVerticalAnchor.Center) + }; +} \ No newline at end of file diff --git a/SecRandom.Core/Models/SubConfigs/Picking/FairDrawSettingsConfig.cs b/SecRandom.Core/Models/SubConfigs/Picking/FairDrawSettingsConfig.cs index 6c413c1fd..bdeb3d031 100644 --- a/SecRandom.Core/Models/SubConfigs/Picking/FairDrawSettingsConfig.cs +++ b/SecRandom.Core/Models/SubConfigs/Picking/FairDrawSettingsConfig.cs @@ -12,9 +12,18 @@ public partial class FairDrawSettingsConfig : ObservableObject [ObservableProperty] private bool _fairDrawTime = true; [ObservableProperty] private FrequencyFunctionMode _frequencyFunction = FrequencyFunctionMode.SquareRoot; [ObservableProperty] private double _frequencyWeight = 1.0; - // Average-gap protection is a mandatory fair-draw pipeline step. Keep these - // compatibility properties for source callers, but do not persist or expose - // them as user settings. + + /// + /// Selects how a fair draw treats students ahead of the class average. + /// keeps the hard average gate; keeps the full roster in the pool and + /// gives an above-threshold student weight 0 instead. Only fair draws read this value; a random draw keeps + /// its equal-probability pool. + /// + [ObservableProperty] private FairDrawMode _mode = FairDrawMode.UniformFirst; + + // Average-gap protection is the mandatory gate of the UniformFirst fair mode; RandomFirst + // replaces it with a zero-probability weight instead. Keep these compatibility properties for + // source callers, but do not persist or expose them as user settings. [JsonIgnore] public bool EnableAvgGapProtection { diff --git a/SecRandom.Core/Models/SubConfigs/Picking/IOrchestratedDrawSettings.cs b/SecRandom.Core/Models/SubConfigs/Picking/IOrchestratedDrawSettings.cs new file mode 100644 index 000000000..5c588b255 --- /dev/null +++ b/SecRandom.Core/Models/SubConfigs/Picking/IOrchestratedDrawSettings.cs @@ -0,0 +1,21 @@ +using SecRandom.Core.Enums.Configs; + +namespace SecRandom.Core.Models.SubConfigs.Picking; + +/// +/// 能被切进 / 切出编排抽取的通道抽取配置:点名、闪抽、抽奖三份配置各自声明 +/// ,共用同一个「进入编排前先记住重复策略」的语义 +/// (DrawModeSelection.SelectOrchestrated / DrawModeSelection.LeaveOrchestrated)。 +/// +/// +/// 故意留在各通道配置上而不是提到共享基类:默认抽取设置没有抽取方式, +/// 不该被这个接口卷进来。 +/// +public interface IOrchestratedDrawSettings +{ + /// 抽取模式(重复策略);值为 时该通道走编排名单。 + DrawMode DrawMode { get; set; } + + /// 进入编排抽取之前生效的重复策略,改回随机 / 公平抽取时恢复。 + DrawMode SampledDrawMode { get; set; } +} \ No newline at end of file diff --git a/SecRandom.Core/Models/SubConfigs/Picking/LotterySettingsConfig.cs b/SecRandom.Core/Models/SubConfigs/Picking/LotterySettingsConfig.cs index ce0f9b035..15c5035a1 100644 --- a/SecRandom.Core/Models/SubConfigs/Picking/LotterySettingsConfig.cs +++ b/SecRandom.Core/Models/SubConfigs/Picking/LotterySettingsConfig.cs @@ -4,7 +4,7 @@ namespace SecRandom.Core.Models.SubConfigs.Picking; -public partial class LotterySettingsConfig : OverridableDrawSettings +public partial class LotterySettingsConfig : OverridableDrawSettings, IOrchestratedDrawSettings { [ObservableProperty] private DrawMode _drawMode = DrawMode.NoRepeat; [ObservableProperty] private ClearRecordMode _clearRecord = ClearRecordMode.Restarted; diff --git a/SecRandom.Core/Models/SubConfigs/Picking/OverridableDrawSettings.cs b/SecRandom.Core/Models/SubConfigs/Picking/OverridableDrawSettings.cs index 04b36d00f..88047d505 100644 --- a/SecRandom.Core/Models/SubConfigs/Picking/OverridableDrawSettings.cs +++ b/SecRandom.Core/Models/SubConfigs/Picking/OverridableDrawSettings.cs @@ -1,4 +1,5 @@ -using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.ComponentModel; +using SecRandom.Core.Enums.Configs; namespace SecRandom.Core.Models.SubConfigs.Picking; @@ -11,4 +12,16 @@ public partial class OverridableDrawSettings : DrawSettingsConfigBase [ObservableProperty] private bool _overrideReminderSettings = false; [ObservableProperty] private bool _overrideMusicSettings = false; [ObservableProperty] private bool _overrideVoiceAnnouncementSettings = false; -} + + /// + /// 进入编排抽取之前生效的重复策略。 + /// + /// + /// 编排抽取不是重复策略(顺序早在抽取前就排定了),所以它只出现在「抽取方式」下拉里,和随机抽取、 + /// 公平抽取摆在同一组;用户一旦选了它,各通道配置的 DrawMode 就必须变成 + /// ,否则抽取端根本不会走编排。这个字段把当时的 + /// 允许重复 / 不重复 / 半重复记下来,改回随机或公平抽取时恢复, + /// 否则一次编排就会把用户的半重复档位悄悄压成不重复。 + /// + [ObservableProperty] private DrawMode _sampledDrawMode = DrawMode.NoRepeat; +} \ No newline at end of file diff --git a/SecRandom.Core/Models/SubConfigs/Picking/QuickDrawSettingsConfig.cs b/SecRandom.Core/Models/SubConfigs/Picking/QuickDrawSettingsConfig.cs index 955b1a5d5..463748999 100644 --- a/SecRandom.Core/Models/SubConfigs/Picking/QuickDrawSettingsConfig.cs +++ b/SecRandom.Core/Models/SubConfigs/Picking/QuickDrawSettingsConfig.cs @@ -3,7 +3,7 @@ namespace SecRandom.Core.Models.SubConfigs.Picking; -public partial class QuickDrawSettingsConfig : OverridableDrawSettings +public partial class QuickDrawSettingsConfig : OverridableDrawSettings, IOrchestratedDrawSettings { [ObservableProperty] private DrawMode _drawMode = DrawMode.NoRepeat; [ObservableProperty] private int _halfRepeat = 1; diff --git a/SecRandom.Core/Models/SubConfigs/Picking/RandomNumberSettingsConfig.cs b/SecRandom.Core/Models/SubConfigs/Picking/RandomNumberSettingsConfig.cs new file mode 100644 index 000000000..8ceb66870 --- /dev/null +++ b/SecRandom.Core/Models/SubConfigs/Picking/RandomNumberSettingsConfig.cs @@ -0,0 +1,72 @@ +using CommunityToolkit.Mvvm.ComponentModel; +using SecRandom.Core.Enums.Configs; +using SecRandom.Core.Services.Profiles; + +namespace SecRandom.Core.Models.SubConfigs.Picking; + +/// +/// 随机数抽取(原“不使用名单”模式)的独立设置。 +/// +/// +/// 这些值只是两个主页数字模式的初始值,不会在用户当场修改范围后回写页面。范围合法性仍由 +/// 与 +/// 共同约束; +/// 页面在应用默认值时会再次夹取,导入的非法配置不会让抽取入口失效。 +/// +public partial class RandomNumberSettingsConfig : ObservableObject +{ + /// 点名页数字范围的起始值。 + [ObservableProperty] private int _rollCallRangeStart = 1; + + /// 点名页数字范围的结束值(含)。 + [ObservableProperty] private int _rollCallRangeEnd = 50; + + /// 抽奖页数字范围的起始值。 + [ObservableProperty] private int _lotteryRangeStart = 1; + + /// 抽奖页数字范围的结束值(含)。 + [ObservableProperty] private int _lotteryRangeEnd = 50; + + /// 重置按钮的行为;默认只清临时剩余数字。 + [ObservableProperty] + private RandomNumberResetBehavior _resetBehavior = RandomNumberResetBehavior.TemporaryOnly; + + /// + /// 把两组范围夹回可抽取区间。返回是否真的改过,调用方据此决定是否落盘。 + /// 导入的配置可能来自旧版本或被手工编辑,因此设置页和主页都要经过这里。 + /// + public bool Normalize() + { + var changed = false; + + var rollCallStart = Math.Max(0, RollCallRangeStart); + if (rollCallStart != RollCallRangeStart) + { + RollCallRangeStart = rollCallStart; + changed = true; + } + + var rollCallEnd = RosterSelection.ClampEnd(RollCallRangeStart, RollCallRangeEnd); + if (rollCallEnd != RollCallRangeEnd) + { + RollCallRangeEnd = rollCallEnd; + changed = true; + } + + var lotteryStart = Math.Max(0, LotteryRangeStart); + if (lotteryStart != LotteryRangeStart) + { + LotteryRangeStart = lotteryStart; + changed = true; + } + + var lotteryEnd = RosterSelection.ClampEnd(LotteryRangeStart, LotteryRangeEnd); + if (lotteryEnd != LotteryRangeEnd) + { + LotteryRangeEnd = lotteryEnd; + changed = true; + } + + return changed; + } +} \ No newline at end of file diff --git a/SecRandom.Core/Models/SubConfigs/Picking/RollCallSettingsConfig.cs b/SecRandom.Core/Models/SubConfigs/Picking/RollCallSettingsConfig.cs index 2f4b621e1..7ff676d4d 100644 --- a/SecRandom.Core/Models/SubConfigs/Picking/RollCallSettingsConfig.cs +++ b/SecRandom.Core/Models/SubConfigs/Picking/RollCallSettingsConfig.cs @@ -3,7 +3,7 @@ namespace SecRandom.Core.Models.SubConfigs.Picking; -public partial class RollCallSettingsConfig : OverridableDrawSettings +public partial class RollCallSettingsConfig : OverridableDrawSettings, IOrchestratedDrawSettings { [ObservableProperty] private DrawMode _drawMode = DrawMode.NoRepeat; [ObservableProperty] private ClearRecordMode _clearRecord = ClearRecordMode.Restarted; 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/Models/SubConfigs/UpdateSettingsConfig.cs b/SecRandom.Core/Models/SubConfigs/UpdateSettingsConfig.cs index 30602e5b0..67abfc722 100644 --- a/SecRandom.Core/Models/SubConfigs/UpdateSettingsConfig.cs +++ b/SecRandom.Core/Models/SubConfigs/UpdateSettingsConfig.cs @@ -12,6 +12,7 @@ public partial class UpdateSettingsConfig : ObservableObject, IJsonOnDeserialize [ObservableProperty] private int _autoUpdateMode = 3; [ObservableProperty] private int _updateModeVersion = 1; [ObservableProperty] private UpdateChannel _updateChannel = UpdateChannel.Release; + [ObservableProperty] private UpdateSource _updateSource = UpdateSource.Auto; [ObservableProperty] [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] private DateTime? _lastCheckTime; diff --git a/SecRandom.Core/Models/Verification/VerificationAlgorithmProfile.cs b/SecRandom.Core/Models/Verification/VerificationAlgorithmProfile.cs index 297820a60..da621d6b0 100644 --- a/SecRandom.Core/Models/Verification/VerificationAlgorithmProfile.cs +++ b/SecRandom.Core/Models/Verification/VerificationAlgorithmProfile.cs @@ -22,5 +22,15 @@ public enum VerificationAlgorithmProfile : byte StudentRandomInternalRuleRepeat = 15, StudentRandomInternalRuleNoRepeat = 16, StudentRandomInternalRuleHalfRepeat = 17, - NumberUniformPermutation = 18 + NumberUniformPermutation = 18, + + /// + /// The round's order was arranged before the draw. Replayed from the committed positions with + /// , and declared to the verifier through + /// fairness.repeatMode = "orchestrated" plus the fairness.orchestration counters. + /// + StudentOrchestrated = 19, + + /// Prize equivalent of . + LotteryOrchestrated = 20 } diff --git a/SecRandom.Core/Models/Verification/VerificationDrawInput.cs b/SecRandom.Core/Models/Verification/VerificationDrawInput.cs index 27a0736be..db78af381 100644 --- a/SecRandom.Core/Models/Verification/VerificationDrawInput.cs +++ b/SecRandom.Core/Models/Verification/VerificationDrawInput.cs @@ -10,4 +10,27 @@ public sealed class VerificationDrawInput public required int Count { get; init; } public IReadOnlyList Candidates { get; init; } = []; public byte[] AuditPayload { get; init; } = []; -} + + /// + /// The draw mode as it appears in the audit payload (repeat, no-repeat, half-repeat, + /// orchestrated). Carried on the input so the proof context projects the same token instead of + /// re-deriving it from the algorithm profile. + /// + public string DrawModeToken { get; init; } = string.Empty; + + /// + /// Which history slice the audit's per-candidate figures were read from. Only the axis name is ever + /// emitted, never the course or the record group behind it. + /// + public string HistoryScope { get; init; } = "global"; + + // Arranged draws only; both null while the draw sampled a pool. + public int? OrchestrationRound { get; init; } + public int? OrchestrationRoundCount { get; init; } + + /// + /// Candidates the internal rule removed outright. The audit payload already declares it; the proof context + /// repeats it in readable form so the pool arithmetic adds up without decoding Base64. + /// + public int ExcludedCandidateCount { get; init; } +} \ No newline at end of file diff --git a/SecRandom.Core/Models/Verification/VerificationSamplingMode.cs b/SecRandom.Core/Models/Verification/VerificationSamplingMode.cs index 920e0465b..bad0ead49 100644 --- a/SecRandom.Core/Models/Verification/VerificationSamplingMode.cs +++ b/SecRandom.Core/Models/Verification/VerificationSamplingMode.cs @@ -7,5 +7,12 @@ public enum VerificationSamplingMode : byte { HistoryBalancedWeighted = 1, InventoryPermutation = 2, - WeightedWithoutReplacement = 3 -} + WeightedWithoutReplacement = 3, + + /// + /// Takes the committed positions instead of sampling. Each drawn candidate carries its 1-based position + /// in the round's arranged order in the weight slot (1..count, dense and unique), the replay + /// returns exactly those candidates in exactly that order and consumes no random material. + /// + SequentialOrder = 4 +} \ No newline at end of file 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..2971fb7ba 100644 --- a/SecRandom.Core/Services/Archive/DataArchiveService.cs +++ b/SecRandom.Core/Services/Archive/DataArchiveService.cs @@ -50,29 +50,20 @@ public sealed class DataArchiveService( /// library was removed, so `theme`/`themes` are neither exported nor committed, and legacy /// archives that still list them are skipped entry by entry instead of failing. /// - private static readonly string[] AllDataRoots = - [ - "config/settings.json", "config/device-uuid.json", "list", "history", "TEMP", "proofs", "audio", "CSES", "images", - "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. + /// 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. /// - public static readonly string[] CloudBackupRoots = + private const string OrchestrationRoot = "config/orchestration"; + + private static readonly string[] AllDataRoots = [ - "config/settings.json", "list", "history", "TEMP", "audio/music", "CSES", "images", "Language", "proofs", "texts" + "config/settings.json", "config/device-uuid.json", OrchestrationRoot, "list", "history", "TEMP", "proofs", + "audio", "CSES", "images", "Language", "logs", "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 +94,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 +145,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 +182,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 +192,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 +215,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()); @@ -655,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))) { } } /// @@ -792,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/ControlNode/ControlRosterListPayloads.cs b/SecRandom.Core/Services/ControlNode/ControlRosterListPayloads.cs new file mode 100644 index 000000000..71e59d753 --- /dev/null +++ b/SecRandom.Core/Services/ControlNode/ControlRosterListPayloads.cs @@ -0,0 +1,46 @@ +using System.Text.Json.Serialization; + +namespace SecRandom.Core.Services.ControlNode; + +/// +/// roster.list 的返回:本机有哪些点名名单 / 奖池。 +/// +/// +/// +/// 只回**名称**,不含成员。操作员发 draw.trigger 时需要一个 list_name 下拉框, +/// 而名单成员(学生姓名)仍然只能走 admin 的 roster.read。把两者合成一条命令, +/// 就等于为了一个下拉框把整份名单摊给所有操作员。 +/// +/// +/// 上限 50 份与 roster.read 的 MaxLists 保持一致:这是"选一项"的列表, +/// 不是导出通道;超过这个数量,控制台应该用别的方式管理名单。 +/// +/// +public sealed record ControlRosterListResponse( + [property: JsonPropertyName("roll_call")] IReadOnlyList RollCall, + [property: JsonPropertyName("lottery")] IReadOnlyList Lottery, + [property: JsonPropertyName("default_roll_call")] string? DefaultRollCall, + [property: JsonPropertyName("default_lottery")] string? DefaultLottery) +{ + /// 列表最多回多少份(点名名单、奖池各自计数)。 + public const int MaxNames = 50; + + /// 去空白、去重并截断到 ,保持原有顺序。 + public static IReadOnlyList Normalize(IEnumerable? names) + { + if (names is null) return []; + + var seen = new HashSet(StringComparer.Ordinal); + var result = new List(); + foreach (var raw in names) + { + var name = (raw ?? string.Empty).Trim(); + if (name.Length == 0 || !seen.Add(name)) continue; + + result.Add(name); + if (result.Count >= MaxNames) break; + } + + return result; + } +} \ No newline at end of file diff --git a/SecRandom.Core/Services/ControlNode/ControlSettingsCatalog.cs b/SecRandom.Core/Services/ControlNode/ControlSettingsCatalog.cs index 6b32b94fb..db61c4c35 100644 --- a/SecRandom.Core/Services/ControlNode/ControlSettingsCatalog.cs +++ b/SecRandom.Core/Services/ControlNode/ControlSettingsCatalog.cs @@ -162,6 +162,12 @@ private static readonly (Type Type, string Id)[] CategoryOrder = "general.basic.accepted_gpl_version", "general.basic.accepted_verification_notice_version", + // 收纳手柄的样式内容:文字、内置图标、导入图片都是这台机器的外观选择, + // 而且图片名指向本机 data/images 下的文件,远程改它只会让手柄变成别的样子或指向空文件。 + "floating_window.stick_to_edge_display_text", + "floating_window.stick_to_edge_display_icon_glyph", + "floating_window.stick_to_edge_display_icon_image", + // 默认记录组:抽取页选择器的初始值。远程改它会让下一节课的点名/抽奖在没人按按钮的情况下 // 从"全部历史"静默变成"只算某个组的历史",现场看到的只是一个更小的权重范围。 "roll_call.history_group", diff --git a/SecRandom.Core/Services/ControlNode/ControlSettingsLabels.cs b/SecRandom.Core/Services/ControlNode/ControlSettingsLabels.cs index d9a905305..cf2244660 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,20 +433,17 @@ 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"), + ["enable_quick_draw_long_press"] = R(FloatingWindow, "S_Interaction_QuickDrawLongPress"), ["do_not_steal_focus"] = R(FloatingWindow, "S_Interaction_DoNotStealFocus"), ["hide_on_foreground"] = R(FloatingWindow, "S_Interaction_HideOnForeground"), ["hide_on_foreground_window_titles"] = R(FloatingWindow, "S_Interaction_HideOnForegroundWindowTitles"), ["hide_on_foreground_process_names"] = R(FloatingWindow, "S_Interaction_HideOnForegroundProcessNames"), - // 自定义文字:内容没有设置页标题可借,故就地三语;开关与字号复用设置页资源。 - ["enable_floating_window_text"] = R(FloatingWindow, "S_Display_CustomText"), - ["floating_window_text"] = L( - "悬浮窗自定义文字", "Floating window custom text", "フローティングウィンドウのカスタムテキスト", - "显示在悬浮窗上的自定义文字内容", "Custom text shown on the floating window", - "フローティングウィンドウに表示するカスタムテキスト"), - ["floating_window_text_font_size"] = R(FloatingWindow, "S_Display_CustomTextSize"), // ---------------- 联动 ["data_source"] = R(Linkage, "S_External_DataSource"), diff --git a/SecRandom.Core/Services/ControlNode/NodeEnrollment.cs b/SecRandom.Core/Services/ControlNode/NodeEnrollment.cs index 67be438fa..16db5d3da 100644 --- a/SecRandom.Core/Services/ControlNode/NodeEnrollment.cs +++ b/SecRandom.Core/Services/ControlNode/NodeEnrollment.cs @@ -58,6 +58,16 @@ public sealed record NodeDeviceCredential( string? ClassId = null, string? ClassName = null); +/// 接入方式:决定设置页把"这台电脑是怎么接进来的"说清楚。 +public static class NodeEnrollmentMethods +{ + /// 地点 ID + 配对码(匿名双因子,装机网管可能没有 SECTL 账号)。 + public const string PairCode = "pairCode"; + + /// 登录 SECTL 账号后由账号接入(桌面专属通道)。 + public const string Account = "account"; +} + /// 一次接入的完整结果。v4 字段与 POST /control/api/enroll 的响应对应。 /// /// NodeId/GroupId/NodeToken 是 v1 的兼容槽位:旧测试与移动端仍会构造它们, @@ -65,6 +75,21 @@ public sealed record NodeDeviceCredential( /// public sealed record NodeEnrollmentRecord { + /// + /// 这条记录是怎么来的()。v4.1 之前写入的记录没有这个字段, + /// 读出来按配对码处理——那时确实只有这一条通道。 + /// + public string EnrollmentMethod { get; init; } = NodeEnrollmentMethods.PairCode; + + /// 账号接入时写下这条记录的 SECTL 用户 ID;配对码接入为空。 + /// + /// 只用于设置页显示"这条接入来自哪个账号",**不参与任何网络请求**, + /// 也绝不会把账号令牌或刷新令牌写进接入记录。 + /// + public string? AccountUserId { get; init; } + + /// 账号接入时的账号显示名(可能为空)。 + public string? AccountName { get; init; } /// v4:服务端分配的设备 ID(与 同值)。 public string DeviceId { get; init; } = string.Empty; @@ -122,6 +147,12 @@ public string NodeToken /// 对外暴露的接入状态:只有"有没有、接在哪、是谁",没有 secret 真值。 public sealed record NodeEnrollmentStatus { + /// 这条接入记录怎么来的;未接入时为空。 + public string? EnrollmentMethod { get; init; } + + /// 账号接入时的账号显示名。 + public string? AccountName { get; init; } + /// 是否持有可用凭据。 public bool HasCredential { get; init; } diff --git a/SecRandom.Core/Services/CoreRuntimeServiceCollectionExtensions.cs b/SecRandom.Core/Services/CoreRuntimeServiceCollectionExtensions.cs index 8b152184f..59a8618f5 100644 --- a/SecRandom.Core/Services/CoreRuntimeServiceCollectionExtensions.cs +++ b/SecRandom.Core/Services/CoreRuntimeServiceCollectionExtensions.cs @@ -5,7 +5,9 @@ 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; namespace SecRandom.Core.Services; @@ -19,12 +21,15 @@ public static IServiceCollection AddCoreRuntimeServices(this IServiceCollection services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddTransient(); services.AddTransient(); + services.AddSingleton(); + services.AddTransient(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); 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.Core/Services/Draw/DrawCommitCoordinator.cs b/SecRandom.Core/Services/Draw/DrawCommitCoordinator.cs index dba994c0e..ce552480e 100644 --- a/SecRandom.Core/Services/Draw/DrawCommitCoordinator.cs +++ b/SecRandom.Core/Services/Draw/DrawCommitCoordinator.cs @@ -69,7 +69,7 @@ public string CommitStudentDraw(StudentDrawCommit commit) commit.Weights, commit.CourseName, roundId, - commit.HistoryGroup); + commit.RecordGroup ?? commit.HistoryGroup); } catch (Exception exception) { @@ -109,7 +109,7 @@ public string CommitLotteryDraw(LotteryDrawCommit commit) { temporaryRecordService.RecordPrizes(commit.PrizeListName, commit.Prizes); profileService.RecordPrizeHistory(commit.Prizes, commit.DrawTime, commit.RequestedCount, commit.PrizeDrawMethod, roundId, - commit.CourseName, commit.HistoryGroup); + commit.CourseName, commit.RecordGroup ?? commit.HistoryGroup); if (hasAssignedStudents) { temporaryRecordService.RecordStudents(studentListName, commit.StudentGenderScope, commit.StudentGroupScope, commit.AssignedStudents!); @@ -123,7 +123,7 @@ public string CommitLotteryDraw(LotteryDrawCommit commit) weights: null, commit.CourseName, roundId, - commit.HistoryGroup); + commit.StudentRecordGroup ?? commit.RecordGroup ?? commit.HistoryGroup); } } catch (Exception exception) 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.Verification.cs b/SecRandom.Core/Services/Draw/DrawEngine.Verification.cs index aa4eae7ef..f5aae6f23 100644 --- a/SecRandom.Core/Services/Draw/DrawEngine.Verification.cs +++ b/SecRandom.Core/Services/Draw/DrawEngine.Verification.cs @@ -37,14 +37,24 @@ public VerificationDrawInput CreateStudentVerificationInput( string courseName, bool includeInternalRules, string rosterDigest = "", - string? historyGroup = null) + string? historyGroup = null, + DrawMode? drawModeOverride = null) { var preparedCandidates = candidates.Where(student => student.IsCandidate).ToList(); if (preparedCandidates.Count == 0 || count <= 0 || count > preparedCandidates.Count) throw new InvalidOperationException("The prepared student pool cannot satisfy this draw."); var drawType = GetStudentDrawType(drawSettingsType); - var drawMode = GetStudentDrawMode(drawSettingsType); + // 覆盖只为一个场景存在:抽奖轮里附带的「分配学生」是这一轮自己的随机分配,点名通道即便配了编排, + // 也不该把那轮的点名排布塞进抽奖证明里。其它调用方一律沿用配置里的模式。 + var drawMode = drawModeOverride ?? GetStudentDrawMode(drawSettingsType); + // An orchestrated draw does not sample: the participant comes from the arranged schedule, and its proof + // must commit those positions (StudentOrchestrated + SequentialOrder) instead of a weighted pool. Routing + // it through the sampled entry point would produce a proof that replays as a random draw, i.e. exactly the + // claim orchestration is supposed to avoid, so fail loudly until the orchestration session builds its own. + if (drawMode == DrawMode.Orchestrated) + throw new InvalidOperationException( + "Orchestrated draws must build their verification input from the arranged schedule."); var executionPolicy = StudentDrawExecutionPolicy.DesktopConfigured(drawType, ConfigData.FairDrawSettings, drawSettingsType switch { @@ -72,16 +82,8 @@ public VerificationDrawInput CreateStudentVerificationInput( var hasInternalRules = includeInternalRules && prepared.WeightedCandidates.Any(candidate => GetBehindSceneSettings(candidate.Candidate) is { IsAttachSettingsEnabled: true }); var algorithmProfile = GetStudentAlgorithmProfile(drawType, drawMode, hasInternalRules); - return new VerificationDrawInput - { - Kind = VerificationDrawKind.Student, - SamplingMode = drawType == DrawType.Fair - ? VerificationSamplingMode.HistoryBalancedWeighted - : VerificationSamplingMode.WeightedWithoutReplacement, - AlgorithmProfile = algorithmProfile, - Count = count, - Candidates = frozen, - AuditPayload = CreateAuditPayload("student", count, frozen, prepared.WeightedCandidates, prepared.HistoryCache, includeInternalRules, new + var auditPayload = CreateAuditPayload("student", count, frozen, prepared.WeightedCandidates, prepared.HistoryCache, + includeInternalRules, new { fairDraw = drawType == DrawType.Fair, algorithmProfile = algorithmProfile.ToString(), @@ -92,15 +94,34 @@ public VerificationDrawInput CreateStudentVerificationInput( // contain a class or a person's name. A narrowed scope is exactly what makes these counts legal to // read as "not the whole history", so it ships with the audit payload rather than being assumed. historyScope = ToHistoryScopeName(courseName, historyGroup), - averageGapProtectionApplied = executionPolicy.DrawType == DrawType.Fair, + averageGapProtectionApplied = executionPolicy.DrawType == DrawType.Fair + && executionPolicy.FairDrawSettings.Mode == FairDrawMode.UniformFirst, candidateCountBeforeAverageGapProtection = preparedCandidates.Count, candidateCountAfterAverageGapProtection = prepared.UsableCandidates.Count, averageGapProtectionThreshold = AverageGapProtectionThreshold, batchSize = count, + // Retained for wire compatibility with the 3.x replay service. The unified weight math no longer + // consumes these horizon/floor constants; they stay declared so an older reader still finds its + // expected keys instead of treating the payload as truncated. The zero-probability policy of the + // random-first mode is already visible per candidate through weightMicros = 0, which is why this + // block needed no new field (the service validates a fixed property allow-list). shareDebtPersonalHorizonRounds = ShareDebtPersonalHorizonRounds, shareDebtDimensionHorizonPerPick = ShareDebtDimensionHorizonPerPick, shareDebtRandomFloor = ShareDebtRandomFloor - }, rosterDigest) + }, rosterDigest, out var excludedCandidateCount); + return new VerificationDrawInput + { + Kind = VerificationDrawKind.Student, + SamplingMode = drawType == DrawType.Fair + ? VerificationSamplingMode.HistoryBalancedWeighted + : VerificationSamplingMode.WeightedWithoutReplacement, + AlgorithmProfile = algorithmProfile, + Count = count, + Candidates = frozen, + AuditPayload = auditPayload, + DrawModeToken = ToAuditName(drawMode), + HistoryScope = ToHistoryScopeName(courseName, historyGroup), + ExcludedCandidateCount = excludedCandidateCount }; } @@ -151,9 +172,28 @@ public VerificationDrawInput CreatePrizeVerificationInput( && weighted.Any(candidate => GetBehindSceneSettings(candidate.Candidate) is { IsAttachSettingsEnabled: true }); var lotteryDrawType = ConfigData.LotterySettings.DrawType; var lotteryDrawMode = ConfigData.LotterySettings.DrawMode; + if (lotteryDrawMode == DrawMode.Orchestrated) + throw new InvalidOperationException( + "Orchestrated draws must build their verification input from the arranged schedule."); var samplingMode = lotteryDrawType == LotteryDrawType.Count && !hasInternalRules ? VerificationSamplingMode.InventoryPermutation : VerificationSamplingMode.WeightedWithoutReplacement; + var auditPayload = CreateAuditPayload("prize", count, frozen, weighted, historyCache, includeInternalRules, new + { + samplingAlgorithm = samplingMode == VerificationSamplingMode.InventoryPermutation + ? "inventory-partial-permutation" + : "weighted-without-replacement", + inventoryEntriesEqualWeight = samplingMode == VerificationSamplingMode.InventoryPermutation, + internalRulesRequireWeightedFallback = samplingMode == VerificationSamplingMode.WeightedWithoutReplacement + && lotteryDrawType == LotteryDrawType.Count + && hasInternalRules, + algorithmProfile = GetLotteryAlgorithmProfile(lotteryDrawType, lotteryDrawMode, hasInternalRules).ToString(), + lotteryMode = lotteryDrawType == LotteryDrawType.Count ? "count" : "pan", + repeatMode = lotteryDrawType == LotteryDrawType.Pan ? ToAuditName(lotteryDrawMode) : null, + halfRepeatLimit = lotteryDrawType == LotteryDrawType.Pan && lotteryDrawMode == DrawMode.HalfRepeat + ? GetLotteryRepeatThreshold() + : (int?)null + }, rosterDigest, out var excludedCandidateCount); return new VerificationDrawInput { Kind = VerificationDrawKind.Prize, @@ -161,22 +201,12 @@ public VerificationDrawInput CreatePrizeVerificationInput( AlgorithmProfile = GetLotteryAlgorithmProfile(lotteryDrawType, lotteryDrawMode, hasInternalRules), Count = count, Candidates = frozen, - AuditPayload = CreateAuditPayload("prize", count, frozen, weighted, historyCache, includeInternalRules, new - { - samplingAlgorithm = samplingMode == VerificationSamplingMode.InventoryPermutation - ? "inventory-partial-permutation" - : "weighted-without-replacement", - inventoryEntriesEqualWeight = samplingMode == VerificationSamplingMode.InventoryPermutation, - internalRulesRequireWeightedFallback = samplingMode == VerificationSamplingMode.WeightedWithoutReplacement - && lotteryDrawType == LotteryDrawType.Count - && hasInternalRules, - algorithmProfile = GetLotteryAlgorithmProfile(lotteryDrawType, lotteryDrawMode, hasInternalRules).ToString(), - lotteryMode = lotteryDrawType == LotteryDrawType.Count ? "count" : "pan", - repeatMode = lotteryDrawType == LotteryDrawType.Pan ? ToAuditName(lotteryDrawMode) : null, - halfRepeatLimit = lotteryDrawType == LotteryDrawType.Pan && lotteryDrawMode == DrawMode.HalfRepeat - ? GetLotteryRepeatThreshold() - : (int?)null - }, rosterDigest) + AuditPayload = auditPayload, + // Count-mode inventory has no repeat semantics of its own, so it declares the sampling shape instead of + // borrowing the configured (and unused) repeat mode. + DrawModeToken = lotteryDrawType == LotteryDrawType.Count ? "inventory" : ToAuditName(lotteryDrawMode), + HistoryScope = "global", + ExcludedCandidateCount = excludedCandidateCount }; } @@ -247,7 +277,11 @@ public VerificationDrawInput CreateNumberVerificationInput(int count, int rangeS AlgorithmProfile = VerificationAlgorithmProfile.NumberUniformPermutation, Count = count, Candidates = candidates, - AuditPayload = auditPayload + AuditPayload = auditPayload, + // The audit declares "no-repeat"; the range holds every ticket exactly once, so the readable context + // repeats that same token rather than inventing a number-specific mode name. + DrawModeToken = "no-repeat", + HistoryScope = "global" }; } @@ -305,13 +339,7 @@ private static VerificationAlgorithmProfile GetLotteryAlgorithmProfile( _ => ConfigData.RollCallSettings.DrawMode }; - private static string ToAuditName(DrawMode drawMode) => drawMode switch - { - DrawMode.Repeat => "repeat", - DrawMode.NoRepeat => "no-repeat", - DrawMode.HalfRepeat => "half-repeat", - _ => "unknown" - }; + private static string ToAuditName(DrawMode drawMode) => DrawModeCatalog.ToToken(drawMode); /// /// Names the history scope a draw's per-candidate history counts came from, for the anonymous audit payload. @@ -404,6 +432,11 @@ private static Guid EnsureRecordId(Prize prize) return prize.RecordId; } + // Midnight UTC of the local day the draw happened on. Written as a real instant rather than a date string so + // older readers that expect a timestamp keep parsing the audit payload. + private static DateTime CoarsenLastDrawn(DateTime value) => + DateTime.SpecifyKind(value.ToUniversalTime().Date, DateTimeKind.Utc); + private static long ToWeightMicros(double weight) { if (double.IsNaN(weight) || double.IsInfinity(weight) || weight < 0) @@ -423,13 +456,14 @@ private static byte[] CreateAuditPayload( IReadOnlyList> weightedCandidates, IReadOnlyDictionary historyCache, bool includeInternalRules, - object? fairness = null, - string rosterDigest = "") + object? fairness, + string rosterDigest, + out int internalExcludedCandidateCount) where TCandidate : IAttachableSettingsObject { + internalExcludedCandidateCount = 0; var historyByRecordId = historyCache.ToDictionary(pair => GetRecordId(pair.Key), pair => pair.Value); Dictionary internalSettingsByRecordId = []; - var internalExcludedCandidateCount = 0; foreach (var weighted in weightedCandidates) { var recordId = GetRecordId(weighted.Candidate); @@ -461,9 +495,13 @@ private static byte[] CreateAuditPayload( internalSettingApplied = internalSettingsByRecordId.GetValueOrDefault(candidate.RecordId) is not null, internalProbability = internalSettingsByRecordId.GetValueOrDefault(candidate.RecordId), historyCount = history?.TotalCount ?? 0, + // Day precision only: a candidate's exact last-drawn instant is a behavioural fingerprint that + // links this record to unrelated proofs (and, with the timestamp field, to a real lesson time). + // The audit needs "how stale is this count", not the minute it happened, so the clock time is + // dropped here and the day survives. lastDrawnUtc = history is null || history.LastDrawnTime == DateTime.MinValue ? (DateTime?)null - : history.LastDrawnTime.ToUniversalTime() + : CoarsenLastDrawn(history.LastDrawnTime) }; }) .ToArray(); 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/FloatingWindow/FloatingWindowDockHandle.cs b/SecRandom.Core/Services/FloatingWindow/FloatingWindowDockHandle.cs new file mode 100644 index 000000000..fb18faea9 --- /dev/null +++ b/SecRandom.Core/Services/FloatingWindow/FloatingWindowDockHandle.cs @@ -0,0 +1,122 @@ +using System.Globalization; +using System.Text; +using SecRandom.Core.Icons; + +namespace SecRandom.Core.Services.FloatingWindow; + +/// +/// 收纳手柄(贴边后那个小方块)的样式规则:取哪种内容、文字最多几个字、哪些字符不允许。 +/// +/// +/// +/// 设置页、悬浮窗渲染和配置归一化都走这里,避免三处各写一套长度/字符判断。 +/// +/// 中文界面仍然只允许“一个字”,这是用户明确要求的单字效果;其它语言(英文、日文)没有单字可说, +/// 按四个字符放宽,既能保留默认的“Go”,也能填一个短词。 +/// +/// +/// 已保存的文字只按 兜底,不按当前语言再截断:切换语言不应 +/// 悄悄改掉(甚至丢掉)用户已经填好的内容,实际显示时的字数限制由设置页输入框负责。 +/// +/// +public static class FloatingWindowDockHandle +{ + /// 收纳手柄样式:图标(默认)。 + public const int IconStyle = 0; + + /// 收纳手柄样式:文字。 + public const int TextStyle = 1; + + /// 收纳手柄样式:方向箭头。 + public const int ArrowStyle = 2; + + /// 图标样式在未配置字形时使用的默认字形(原“点名”头像图标)。 + public const string DefaultIconGlyph = FluentIcons.PeopleFilled; + + /// 箭头样式用的字形:箭头本身不再用 “<” / “>” 字符画。 + public const string LeftArrowGlyph = FluentIcons.ChevronLeftFilled; + + public const string RightArrowGlyph = FluentIcons.ChevronRightFilled; + + /// 中文界面的单字上限。 + public const int ChineseMaxTextLength = 1; + + /// 其它语言的字数上限:只有中文才讲“单字”,不能让英文被迫只写一个字母。 + public const int OtherMaxTextLength = 4; + + /// 配置里能存的长度上限,保证切到中文界面时也不会把已存的四个字符砍掉。 + public const int StoredMaxTextLength = OtherMaxTextLength; + + public static bool IsIconStyle(int style) => style == IconStyle; + + public static bool IsTextStyle(int style) => style == TextStyle; + + public static bool IsChineseUi(CultureInfo? culture) => + string.Equals(culture?.TwoLetterISOLanguageName, "zh", StringComparison.OrdinalIgnoreCase); + + /// 当前界面语言下允许输入的字数。 + public static int GetMaxTextLength(CultureInfo? culture) => + IsChineseUi(culture) ? ChineseMaxTextLength : OtherMaxTextLength; + + /// + /// 按“允许的字符 + 最大长度”整理用户输入:去掉首尾空白、emoji 与控制字符;空白结果等于未填写。 + /// + public static string NormalizeText(string? text, int maxLength) + { + if (maxLength < 1) + maxLength = 1; + + if (string.IsNullOrWhiteSpace(text)) + return string.Empty; + + var builder = new StringBuilder(Math.Min(text.Length, maxLength)); + var count = 0; + foreach (var rune in text.Trim().EnumerateRunes()) + { + if (count >= maxLength) + break; + if (Rune.IsControl(rune) || IsEmojiRune(rune)) + continue; + + builder.Append(rune.ToString()); + count++; + } + + return builder.ToString(); + } + + /// + /// 实际显示的文字:没填就回退到本地化默认文字;对已存的值只过滤 emoji 并按硬上限截断。 + /// + public static string ResolveText(string? text, string fallback) + { + var normalized = NormalizeText(text, StoredMaxTextLength); + return normalized.Length > 0 ? normalized : fallback; + } + + /// + /// 文字越长字号越小:单字保持原来的比例,多字符语言也不会撑出方块。 + /// + public static double GetTextFontScale(int textLength) => textLength switch + { + <= 1 => 0.42, + 2 => 0.34, + _ => 0.26 + }; + + /// + /// 是否是 emoji 字符。字符输入框只挡住 emoji,不挡普通标点,因为“一个字”允许用户填任意可见字符。 + /// + private static bool IsEmojiRune(Rune rune) + { + var value = rune.Value; + return value is >= 0x1F000 and <= 0x1FAFF // emoji 主体与区域指示符 + or >= 0x2600 and <= 0x27BF // 杂项符号与 dingbats(☀ ★ ❤ 等 emoji 来源) + or >= 0x2B00 and <= 0x2BFF // ⬛ ⭐ 等 + or >= 0xFE00 and <= 0xFE0F // 变体选择符:把普通字符变成 emoji 的那个 + or 0x200D // ZWJ 组合符 + or 0x20E3 // 键帽组合符 + or 0x3030 or 0x303D or 0x3297 or 0x3299 // 〰 〽 ㊗ ㊙ + or 0x00A9 or 0x00AE or 0x203C or 0x2049 or 0x2122 or 0x2139 or 0x24C2; // © ® ‼ ⁉ ™ ℹ Ⓜ + } +} \ No newline at end of file diff --git a/SecRandom.Core/Services/FloatingWindow/QuickDrawLongPressGesture.cs b/SecRandom.Core/Services/FloatingWindow/QuickDrawLongPressGesture.cs new file mode 100644 index 000000000..8c8e06c39 --- /dev/null +++ b/SecRandom.Core/Services/FloatingWindow/QuickDrawLongPressGesture.cs @@ -0,0 +1,278 @@ +using System.Collections.Generic; +using Avalonia; +using Avalonia.Media; + +namespace SecRandom.Core.Services.FloatingWindow; + +/// +/// 悬浮窗「闪抽」长按快选的全部纯计算:按住时长 → 环进度、环上的位置 → 环颜色、 +/// 指针纵向位置 → 抽取人数、球与整块快选面板的落位与夹紧。 +/// +/// +/// 这里刻意不碰窗口、指针与合成器,只做数值决策,因此可以在 xUnit 里逐条钉住边界: +/// 人数上限、拖动取消距离、时长夹紧、环颜色端点、6 行滑轨到人数(含"退出")的映射、 +/// 球与面板不出屏。窗口层只负责把结果贴到 FloatingWindow 上。 +/// +public static class QuickDrawLongPressGesture +{ + /// 长按最多一次抽多少人。 + public const int MaxCount = 5; + + /// 快选滑轨的行数:5、4、3、2、1 与"退出"。 + public const int OptionCount = MaxCount + 1; + + /// + /// 刚展开、还没滑动时默认指向的人数。手指按住期间给的暗示是"我就要 1 个人", + /// 真要多抽才需要往下/往上找到对应行。 + /// + public const int DefaultCount = 1; + + /// 按住后指针偏离超过这个距离(DIP)就不算长按,改判为拖动窗口。 + public const double DragCancelDistance = 14; + + /// + /// 触控/手写笔按住时的容差(DIP)。手指按住会自然漂移十几 DIP,沿用鼠标的 + /// 会把"点一下"误判成拖窗,长按也更容易被打断。 + /// + public const double TouchDragCancelDistance = 24; + + /// 滑轨上真正把选中行切到下一行所需的纵向位移(DIP,鼠标)。 + public const double SelectionActivationDistance = 8; + + /// 触控时切换选中行的纵向位移:比鼠标多留一点,避免按住时的轻微滑动改掉人数。 + public const double TouchSelectionActivationDistance = 12; + + /// 长按时长的下界,避免 0 或负数把环一按到底。 + public const int MinHoldDurationMilliseconds = 40; + + /// 长按时长的上界,避免配置里写了个天文数字后再也等不到完成。 + public const int MaxHoldDurationMilliseconds = 3000; + + /// 配置缺字段或非法时的长按时长回退值。 + public const int DefaultHoldDurationMilliseconds = 500; + + /// 鼠标右键按下时用的长按时长(只做一次确认,不再等满整个配置时长)。 + /// + /// Windows 会把触控"长按"先攒在自己的按住时间里,攒够之后才以一次鼠标右键按下的形式 + /// 重新投递(松手时补一次右键抬起)。也就是说用户真正的按住时长已经用掉了,这里再等一整个 + /// 等于让人多按半秒;但也不能一按下就弹面板, + /// 否则一次快速的右键点击也会把人送进快选。取一个只够区分"按下即松"和"继续按住"的时长。 + /// + public const int SecondaryButtonHoldDurationMilliseconds = 160; + + /// 球的最小直径(DIP),再小就看不清、也点不准。 + public const double MinOrbSize = 44; + + /// 球的最大直径(DIP),再大就盖住了滑轨。 + public const double MaxOrbSize = 96; + + /// 快选面板四周留白,同时给球的光晕留出绘制空间。 + public const double SlabPadding = 8; + + /// 滑轨与球之间的间距。 + public const double PickerGap = 14; + + /// 滑轨行间距。 + public const double RowSpacing = 4; + + /// 长按环的默认起点色(宿主未指定主题色时使用)。 + public static readonly Color RingStartColor = Color.Parse("#2E8BFF"); + + /// 长按环的默认完成色(宿主未指定主题色时使用)。 + public static readonly Color RingEndColor = Color.Parse("#22C55E"); + + /// 把设置里的长按时长夹到可执行区间。 + public static int NormalizeHoldDuration(int milliseconds) + { + return Math.Clamp(milliseconds, MinHoldDurationMilliseconds, MaxHoldDurationMilliseconds); + } + + /// 这次按住要走多长的进度:右键(触控长按在 Windows 上的替身)只走一段确认时长。 + public static int ResolveHoldDuration(int holdDurationMilliseconds, bool isSecondaryButton) + { + var duration = NormalizeHoldDuration(holdDurationMilliseconds); + return isSecondaryButton + ? Math.Min(duration, SecondaryButtonHoldDurationMilliseconds) + : duration; + } + + /// 按住已经过了多少比例:0 刚到 1 完成,超出时长后保持 1。 + public static double ResolveProgress(long elapsedMilliseconds, int holdDurationMilliseconds) + { + var duration = NormalizeHoldDuration(holdDurationMilliseconds); + if (elapsedMilliseconds <= 0) + return 0; + if (elapsedMilliseconds >= duration) + return 1; + + return elapsedMilliseconds / (double)duration; + } + + /// 指针相对按下的位置是否已经超出长按容差(超出即取消长按、转为拖动窗口)。 + public static bool ShouldCancelForDrag(Point start, Point current, double threshold = DragCancelDistance) + { + var deltaX = current.X - start.X; + var deltaY = current.Y - start.Y; + return (deltaX * deltaX) + (deltaY * deltaY) > threshold * threshold; + } + + /// 按指针类型取长按容差:触控/手写笔用更大的容差,鼠标沿用精确的 14 DIP。 + public static double ResolveDragCancelDistance(bool isTouchOrPen) + { + return isTouchOrPen ? TouchDragCancelDistance : DragCancelDistance; + } + + /// 按指针类型取滑轨切换选中行所需的纵向位移。 + public static double ResolveSelectionActivationDistance(bool isTouchOrPen) + { + return isTouchOrPen ? TouchSelectionActivationDistance : SelectionActivationDistance; + } + + /// 按指针类型判断这次位移是否已经超出长按容差。 + public static bool ShouldCancelForDrag(Point start, Point current, bool isTouchOrPen) + { + return ShouldCancelForDrag(start, current, ResolveDragCancelDistance(isTouchOrPen)); + } + + /// + /// 环上某一点的颜色: 是"从起点算起占已完成部分的进度", + /// 0 是蓝色起点、1 是绿色头部。头部始终是绿色,整圈填满时才呈现完整的蓝→绿渐变。 + /// + public static Color ResolveRingColor(double fraction) + { + return LerpColor(RingStartColor, RingEndColor, fraction); + } + + /// + /// 在两个颜色之间按比例插值;宿主把主题强调色传给进度环时用它生成"起点色 → 头部色"。 + /// + public static Color LerpColor(Color start, Color end, double fraction) + { + var t = Math.Clamp(fraction, 0, 1); + return Color.FromArgb( + 255, + Lerp(start.R, end.R, t), + Lerp(start.G, end.G, t), + Lerp(start.B, end.B, t)); + } + + /// 把颜色朝 方向提亮 (0 原样、1 全白)。 + public static Color Lighten(Color color, double amount) + { + var t = Math.Clamp(amount, 0, 1); + return Color.FromArgb( + 255, + Lerp(color.R, 255, t), + Lerp(color.G, 255, t), + Lerp(color.B, 255, t)); + } + + /// 球直径:跟随收纳球尺寸,但夹在可读可点的区间里。 + public static double ResolveOrbSize(int dockedWindowSize) + { + return Math.Clamp(dockedWindowSize, MinOrbSize, MaxOrbSize); + } + + /// + /// 滑轨的自上而下行序:滑轨在球的左侧时整列是 5、4、3、2、1、"退出", + /// 在球的右侧时整列镜像成"退出"、1、2、3、4、5——退出永远贴屏幕边缘那一端。 + /// + public static IReadOnlyList ResolveRowCounts(bool pickerOnLeft) + { + var rows = new int[OptionCount]; + for (var index = 0; index < OptionCount; index++) + rows[index] = pickerOnLeft ? MaxCount - index : index; + + return rows; + } + + /// 滑轨永远放在浮窗的对侧:浮窗在左就从右边弹出,浮窗在右就从左边弹出。 + public static bool ResolvePickerOnLeft(bool windowOnLeft) + { + return !windowOnLeft; + } + + /// 某一人数在行序里的下标;找不到时回到默认人数的行,再找不到就回到首行。 + public static int ResolveRowIndex(IReadOnlyList rowCounts, int count) + { + for (var index = 0; index < rowCounts.Count; index++) + { + if (rowCounts[index] == count) + return index; + } + + if (count != DefaultCount) + return ResolveRowIndex(rowCounts, DefaultCount); + + return 0; + } + + /// + /// 指针落在滑轨的哪一行,并按行序换回人数(0 表示"退出")。 + /// 超出滑轨范围时夹到首/末行,所以"一直滑到底"一定是行序两端的那一项。 + /// + public static int ResolveCount( + double pointerY, + double pickerTop, + double pickerHeight, + IReadOnlyList rowCounts) + { + if (pickerHeight <= 0 || rowCounts.Count == 0) + return DefaultCount; + + // 行高与行间距相加正好是 (pickerHeight + RowSpacing) / 行数,行边界因此对得上真实布局。 + var step = (pickerHeight + RowSpacing) / rowCounts.Count; + var index = (int)Math.Floor((pointerY - pickerTop) / step); + index = Math.Clamp(index, 0, rowCounts.Count - 1); + return rowCounts[index]; + } + + /// 某一行的中心相对滑轨顶部的偏移,用于把默认人数那一行对准按下点。 + public static double ResolveRowCenterOffset(int rowIndex, double rowHeight) + { + var rows = Math.Max(0, rowIndex); + return (rows * (rowHeight + RowSpacing)) + (rowHeight / 2); + } + + /// 整块快选面板(滑轨 + 球)的尺寸与滑轨在面板内的矩形。 + public static QuickPickLayout ResolveLayout( + double orbSize, + double pickerWidth, + int rowCount, + double rowHeight, + bool pickerOnLeft) + { + var rows = Math.Max(1, rowCount); + var pickerHeight = (rows * rowHeight) + ((rows - 1) * RowSpacing); + var slabHeight = Math.Max(orbSize, pickerHeight) + (SlabPadding * 2); + var slabWidth = (SlabPadding * 2) + pickerWidth + PickerGap + orbSize; + var pickerX = pickerOnLeft + ? SlabPadding + : SlabPadding + orbSize + PickerGap; + var pickerY = (slabHeight - pickerHeight) / 2; + + return new QuickPickLayout( + new Size(slabWidth, slabHeight), + new Rect(pickerX, pickerY, pickerWidth, pickerHeight), + pickerOnLeft); + } + + /// 球心在面板内的位置:跟随指针,但始终留出边距,不贴到面板边缘外。 + public static Point ResolveOrbCenter(Point pointerInWindow, Size windowSize, double orbSize) + { + var radius = orbSize / 2; + var inset = radius + SlabPadding; + + return new Point( + Math.Clamp(pointerInWindow.X, inset, Math.Max(inset, windowSize.Width - inset)), + Math.Clamp(pointerInWindow.Y, inset, Math.Max(inset, windowSize.Height - inset))); + } + + private static byte Lerp(byte from, byte to, double t) + { + return (byte)Math.Round(from + ((to - from) * t)); + } +} + +/// 快选面板的布局结果:面板尺寸、滑轨矩形、滑轨是否在球的左侧。 +public readonly record struct QuickPickLayout(Size WindowSize, Rect PickerRect, bool PickerOnLeft); \ No newline at end of file diff --git a/SecRandom.Core/Services/FloatingWindow/QuickDrawResultGridLayout.cs b/SecRandom.Core/Services/FloatingWindow/QuickDrawResultGridLayout.cs new file mode 100644 index 000000000..184967eba --- /dev/null +++ b/SecRandom.Core/Services/FloatingWindow/QuickDrawResultGridLayout.cs @@ -0,0 +1,103 @@ +using System; + +namespace SecRandom.Core.Services.FloatingWindow; + +/// +/// 浮窗结果卡的网格排版决策:给定人数、可用宽高和单张卡片尺寸,决定一行放几张。 +/// +/// +/// +/// 列数先按可用区域的宽高比推一个"愿意铺多宽"的理想值,再用两条硬约束收窄: +/// 一是屏幕宽度最多能并排放下几张(长姓名会把卡片撑宽,不能让它把列数压成 1), +/// 二是至少留两行(4 个人是 2×2、6 个人在正常横向屏幕上 3×2,而不是又拉成一条长龙)。 +/// 可用区域偏窄偏高时理想值会掉到 1,此时 4 人以上仍保底 2 列, +/// 所以竖屏/窄窗口得到的是 2 列多行,而不是一路竖着排。 +/// +/// +/// 这里只做纯数值决策,不碰控件与窗口,因此 SecRandom.Core.Tests 可以直接钉住 +/// "4 人→2 列、宽屏 6 人→3 列、窄高屏 6 人→2 列"这些用户能看见的结果。 +/// +/// +public static class QuickDrawResultGridLayout +{ + /// + /// 估算列数时使用的名义卡片宽高比。刻意不用实测宽度:长姓名会把单张卡片撑到 + /// 300–400 DIP,实测比例会把 4 个人算成 1 列,而用户要的是 2×2。 + /// + public const double NominalCardAspectRatio = 1.5; + + /// + /// 返回一行应放几张卡片; 为 0 时返回 0。 + /// + /// 结果卡总数。 + /// 结果区可用宽度(DIP)。 + /// 结果区可用高度(DIP)。 + /// 单张卡片的最大自然宽度(DIP)。 + /// 单张卡片的最大自然高度(DIP)。 + public static int ResolveColumns( + int itemCount, + double availableWidth, + double availableHeight, + double cardWidth, + double cardHeight) + { + if (itemCount <= 0) + return 0; + + // 量测还没落到真实窗口上时可能拿到无穷/0;收敛成 1 让后面的夹紧逻辑仍然给出可执行结果。 + var width = IsPositiveFinite(availableWidth) ? availableWidth : 1; + var height = IsPositiveFinite(availableHeight) ? availableHeight : 1; + var itemWidth = IsPositiveFinite(cardWidth) ? cardWidth : 1; + var itemHeight = IsPositiveFinite(cardHeight) ? cardHeight : 1; + + var widthFit = width / itemWidth; + var maxByWidth = widthFit >= itemCount + ? itemCount + : Math.Max(1, (int)Math.Floor(widthFit)); + // 最多铺两行:6 个人不会排成 4+2,10 个人也不会先铺 9 个再挂一个。 + var maxByBalance = itemCount <= 2 ? itemCount : Math.Max(2, (int)Math.Ceiling(itemCount / 2.0)); + var maxColumns = Math.Max(1, Math.Min(itemCount, Math.Min(maxByWidth, maxByBalance))); + + var availableAspect = width / height; + var ideal = (int)Math.Clamp( + Math.Round( + Math.Sqrt(itemCount * availableAspect / NominalCardAspectRatio), + MidpointRounding.AwayFromZero), + 1d, + itemCount); + + // 4 人以上、宽度又允许时至少两列:竖屏也保持"两个人一排",而不是四个人竖成一列。 + var minColumns = itemCount >= 4 && maxByWidth >= 2 ? 2 : 1; + var columns = Math.Clamp(ideal, minColumns, maxColumns); + + // 最后一行只剩 1 张时,如果多一列能同时减少行数,就补到那一列,避免孤零零一张。 + while (columns < maxColumns + && LastRowItemCount(itemCount, columns) == 1 + && RowCount(itemCount, columns + 1) < RowCount(itemCount, columns)) + { + columns++; + } + + // 行高装不下时优先加列(加列会减少行数);已经到宽度/行数上限就交给外层纵向滚动。 + while (RowCount(itemCount, columns) * itemHeight > height && columns < maxColumns) + columns++; + + return columns; + } + + private static int RowCount(int itemCount, int columns) + { + return (itemCount + columns - 1) / columns; + } + + private static int LastRowItemCount(int itemCount, int columns) + { + var rows = RowCount(itemCount, columns); + return itemCount - ((rows - 1) * columns); + } + + private static bool IsPositiveFinite(double value) + { + return double.IsFinite(value) && value > 0; + } +} \ No newline at end of file diff --git a/SecRandom.Core/Services/Ipc/AutomationCommandCatalog.cs b/SecRandom.Core/Services/Ipc/AutomationCommandCatalog.cs new file mode 100644 index 000000000..d59e7861b --- /dev/null +++ b/SecRandom.Core/Services/Ipc/AutomationCommandCatalog.cs @@ -0,0 +1,73 @@ +namespace SecRandom.Core.Services.Ipc; + +/// +/// One method descriptor. This is the single source of truth shared by the local v2 IPC +/// registry, the URL adapter and (later) the control-plane dispatcher. +/// +public sealed record AutomationCommandDescriptor( + string Name, + string Since, + IReadOnlyList Scopes, + string Params, + string Result); + +/// +/// The v2 method catalog. Descriptors are intentionally hand-written rather than reflected +/// from handler signatures: the wire contract is public API and must not change because a +/// C# parameter was renamed. +/// +public static class AutomationCommandCatalog +{ + public const string ProtocolVersion = "2.0"; + + public static IReadOnlyList Methods { get; } = + [ + new("system.ping", "2.0", [], "-", "{pong,serverTimeUtc}"), + new("system.info", "2.0", [], "-", "{appVersion,platform,protocolVersions,simpleMode,lotteryEnabled}"), + new("system.capabilities", "2.0", [], "-", "{protocolVersions,features,methods:[...]}"), + new("system.integration.status", "2.0", [], "-", "{urlRegistered,autostartEnabled,portable}"), + + new("state.windows", "2.0", [AutomationScopes.ReadState], "-", "{main,settings,floating,quickDraw}"), + new("state.draw", "2.0", [AutomationScopes.ReadState], "-", "{rollCall,lottery,quickDraw}"), + new("state.runtime", "2.0", [AutomationScopes.ReadState], "-", "{profile,linkage,control}"), + + new("window.show", "2.0", [AutomationScopes.WriteWindow], "{target,page?}", "{visible,page}"), + new("window.hide", "2.0", [AutomationScopes.WriteWindow], "{target}", "{visible:false}"), + new("window.toggle", "2.0", [AutomationScopes.WriteWindow], "{target}", "{visible}"), + new("window.navigate", "2.0", [AutomationScopes.WriteWindow], "{target,page}", "{visible:true,page}"), + + new("settings.schema", "2.0", [AutomationScopes.ReadSettings], "-", "{revision,categories}"), + new("settings.get", "2.0", [AutomationScopes.ReadSettings], "{paths?}", "{values,revision}"), + new("settings.set", "2.0", [AutomationScopes.WriteSettings], "{patch}", "{values,requiresRestart,rejected?}"), + new("settings.page.open", "2.0", [AutomationScopes.WriteSettings], "{page,preview?}", "{visible,page,preview}"), + + new("roster.lists", "2.0", [AutomationScopes.ReadRoster], "-", "{students,prizes,activeStudentList,activePrizePool}"), + new("roster.read", "2.0", [AutomationScopes.ReadRoster], "{kind,list?}", "{lists,truncated}"), + new("roster.write", "2.0", [AutomationScopes.WriteRoster], "{kind,list,mode,activate?,members}", "{list,added,updated,total,backup}"), + new("roster.activate", "2.0", [AutomationScopes.WriteRoster], "{kind,list}", "{active}"), + + new("draw.rollCall.trigger", "2.0", [AutomationScopes.WriteDraw], "{list?,count?,gender?,group?}", "{status,reason,list,drawn}"), + new("draw.rollCall.configure", "2.0", [AutomationScopes.WriteDraw], "{list?,count?,gender?,group?}", "{applied}"), + new("draw.rollCall.start", "2.0", [AutomationScopes.WriteDraw], "-", "{accepted,state}"), + new("draw.rollCall.stop", "2.0", [AutomationScopes.WriteDraw], "-", "{stopped}"), + new("draw.rollCall.reset", "2.0", [AutomationScopes.WriteDraw], "-", "{reset}"), + new("draw.quick.trigger", "2.0", [AutomationScopes.WriteDraw], "-", "{record}"), + new("draw.lottery.trigger", "2.0", [AutomationScopes.WriteDraw], "{pool?,list?,count?,gender?,group?}", "{status,reason,list,drawn}"), + new("draw.lottery.configure", "2.0", [AutomationScopes.WriteDraw], "{pool?,list?,count?,gender?,group?}", "{applied}"), + new("draw.lottery.start", "2.0", [AutomationScopes.WriteDraw], "-", "{accepted,state}"), + new("draw.lottery.stop", "2.0", [AutomationScopes.WriteDraw], "-", "{stopped}"), + new("draw.lottery.reset", "2.0", [AutomationScopes.WriteDraw], "-", "{reset}"), + new("draw.result", "2.0", [AutomationScopes.ReadHistory], "{channel}", "{roundId,records,at}"), + new("draw.await", "2.0", [AutomationScopes.ReadHistory], "{roundId?,timeoutMs?}", "{completed,result?,pending?}"), + + new("history.query", "2.0", [AutomationScopes.ReadHistory], "{kind,name,from?,to?,limit?,offset?}", "{entries,total,hasMore}"), + new("history.summary", "2.0", [AutomationScopes.ReadHistory], "{kind,name}", "{members,draws,lastAt}"), + + new("events.subscribe", "2.0", [AutomationScopes.ReadEvents], "{types?}", "{subscribed,seqStart}"), + new("events.unsubscribe", "2.0", [AutomationScopes.ReadEvents], "-", "{subscribed}"), + new("events.status", "2.0", [AutomationScopes.ReadEvents], "-", "{subscribed,queued,dropped}") + ]; + + public static AutomationCommandDescriptor? Find(string method) => + Methods.FirstOrDefault(m => string.Equals(m.Name, method, StringComparison.Ordinal)); +} \ No newline at end of file diff --git a/SecRandom.Core/Services/Ipc/AutomationErrorCodes.cs b/SecRandom.Core/Services/Ipc/AutomationErrorCodes.cs new file mode 100644 index 000000000..48b77adc2 --- /dev/null +++ b/SecRandom.Core/Services/Ipc/AutomationErrorCodes.cs @@ -0,0 +1,44 @@ +namespace SecRandom.Core.Services.Ipc; + +/// +/// Stable v2 error codes. Keep these values byte-compatible with +/// docs/ipc-url-protocol.md; v1 codes are separate and must not change. +/// +public static class AutomationErrorCodes +{ + public const string InvalidRequest = "invalid_request"; + public const string UnsupportedVersion = "unsupported_version"; + public const string UnsupportedMethod = "unsupported_method"; + public const string InvalidParameter = "invalid_parameter"; + public const string MissingParameter = "missing_parameter"; + public const string NotFound = "not_found"; + public const string PageNotFound = "page_not_found"; + public const string PageNotAvailable = "page_not_available"; + public const string InvalidState = "invalid_state"; + public const string FeatureDisabled = "feature_disabled"; + public const string AuthorizationDenied = "authorization_denied"; + public const string LocalVerificationRequired = "local_verification_required"; + public const string OobeRequired = "oobe_required"; + public const string IntegrityConfirmationRequired = "integrity_confirmation_required"; + public const string IpcDisabled = "ipc_disabled"; + public const string UrlActivationForbidden = "url_activation_forbidden"; + public const string RateLimited = "rate_limited"; + public const string Busy = "busy"; + public const string Timeout = "timeout"; + public const string InternalError = "internal_error"; + public const string PipeUnavailable = "pipe_unavailable"; +} + +public static class AutomationScopes +{ + public const string ReadState = "read.state"; + public const string ReadRoster = "read.roster"; + public const string ReadSettings = "read.settings"; + public const string ReadHistory = "read.history"; + public const string ReadEvents = "read.events"; + public const string WriteWindow = "write.window"; + public const string WriteSettings = "write.settings"; + public const string WriteRoster = "write.roster"; + public const string WriteDraw = "write.draw"; + public const string Lifecycle = "lifecycle"; +} \ No newline at end of file diff --git a/SecRandom.Core/Services/Notification/TextLibraryPrompt.cs b/SecRandom.Core/Services/Notification/TextLibraryPrompt.cs new file mode 100644 index 000000000..03b2fba37 --- /dev/null +++ b/SecRandom.Core/Services/Notification/TextLibraryPrompt.cs @@ -0,0 +1,65 @@ +using System.Globalization; + +namespace SecRandom.Core.Services.Notification; + +/// +/// 文案库导入抽屉里可一键复制的 AI 提示词。 +/// +/// +/// +/// 提示词本身固定为英文,只有"用哪种语言回复我 / 用哪种语言写文案"这两句跟随软件界面语言, +/// 因为用户会把整段发给任意对话式 AI,英文指令的通用性最好。两句必须都带上语言: +/// 只写文案语言的话,AI 仍会用英文提问和解释,用户看到的就是"软件是中文、AI 却全程英文"。 +/// +/// +/// 输出约束必须与 的校验保持一致(JSON 字符串数组、 +/// 单条 ≤ 字符、{result} 占位符只出现一次、 +/// 整体不超过 字符), +/// 否则 AI 生成的数组无法直接粘贴回导入框;Template 段给出的示例本身也必须能通过导入解析。 +/// +/// +public static class TextLibraryPrompt +{ + private const string OutputLanguageToken = "__OUTPUT_LANGUAGE__"; + + private const string Template = + """ + I am preparing the text library of SecRandom, a random draw app. Each entry is a short text that the app shows as a fullscreen result message, and its {result} placeholder is replaced with the drawn name or prize. + + Reply to me in __OUTPUT_LANGUAGE__. Before writing anything, ask me these two questions and wait for my answers: + 1. What kind of texts do you need? + 2. How many texts do you need? (1 to 500) + + After I answer, write exactly that many texts in __OUTPUT_LANGUAGE__. Follow these format rules: + - Reply with exactly one fenced code block tagged json, and put nothing outside the code block + - The code block contains one JSON array of strings, following the template below + - Every item is one single-line text with no numbering or list markers + - Every item is 2 to 200 characters, and the whole array stays under 14000 characters + - Put the {result} placeholder exactly once in every item, where the drawn result belongs + - Do not ask more questions once you know the kind and the count + + Template: + ```json + [ + "Example text with {result}", + "Another example with {result}" + ] + ``` + + Replace the two example texts with the requested content and keep the JSON valid + """; + + /// + /// 按软件界面语言生成提示词:正文永远是英文,只有回复语言与文案语言两处语言名随界面语言变化。 + /// + /// 界面语言;为空或不受支持时按英文输出。 + public static string Build(CultureInfo? culture) => + Template.Replace(OutputLanguageToken, OutputLanguageName(culture), StringComparison.Ordinal); + + private static string OutputLanguageName(CultureInfo? culture) => culture?.TwoLetterISOLanguageName switch + { + "zh" => "Simplified Chinese", + "ja" => "Japanese", + _ => "English" + }; +} \ No newline at end of file diff --git a/SecRandom.Core/Services/Notification/TextLibraryService.cs b/SecRandom.Core/Services/Notification/TextLibraryService.cs index 79803e8b6..1ea6f54de 100644 --- a/SecRandom.Core/Services/Notification/TextLibraryService.cs +++ b/SecRandom.Core/Services/Notification/TextLibraryService.cs @@ -13,8 +13,8 @@ namespace SecRandom.Core.Services.Notification; /// /// /// 落盘位置是 data/texts/library.json,刻意不在 data/config/ 下: -/// 备份归档会把 config/ 里除 device-uuid 之外的路径折叠成 config/settings.json, -/// 放进去等于让文案库在备份/还原里被静默吞掉。 +/// 备份归档会把 config/ 里的路径折叠成 config/settings.json(只有 device-uuid 与 +/// orchestration 另有自己的段),放进去等于让文案库在备份/还原里被静默吞掉。 /// /// /// 计数是"尽力而为"的公平性辅助量,不是账本:文件损坏时整库重建默认 30 条并保存, 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.Core/Services/Presentation/AdaptiveTheme.cs b/SecRandom.Core/Services/Presentation/AdaptiveTheme.cs new file mode 100644 index 000000000..175f771db --- /dev/null +++ b/SecRandom.Core/Services/Presentation/AdaptiveTheme.cs @@ -0,0 +1,293 @@ +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; + + /// 整块卡片(含文字)的不透明度;手动构造方案时默认不透明。 + public double SurfaceOpacity { get; init; } = 1; + + /// 计算中位数处可见文字亮度所需的桌面亮度。 + public double BackdropMedianLuminance { get; init; } +} + +/// +/// 把"背景有多亮"翻译成"用白字还是黑字、卡片底压多深"。 +/// +/// +/// +/// 只用两种前景(白/黑)是刻意的:这正是"自适应主题色"的需求本身,也是唯一在 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; + var luminance = RelativeLuminance(surface); + return Build(isDarkTheme, 1.0, BackdropLuminance.FromPercentiles(luminance, luminance, luminance)); + } + + /// + /// 按背景亮度分布求解自适应方案。 只在亮度中位数恰好 + /// 落在分界线上时充当平局判定,正常情况完全由桌面决定。 + /// + /// + /// 整块卡片在窗口里的实际不透明度(0–1)。通知窗的「不透明度」设置作用在卡片整体上, + /// 所以桌面会按 1 - 不透明度 的比例透上来,判定必须把这一层也算进去,否则 + /// 低不透明度下会出现"白字压在被桌面冲淡的浅卡片上"。 + /// + /// + /// 半透明卡片压在一张花壁纸/正在放的 PPT 上时,卡片左边缘与右边缘的最终亮度可能相差很大, + /// 所以前景不能只对中位数成立:它必须对 与 + /// 合成出来的两端都尽量清晰。两端做不到就依次把底色 + /// 压得更实,最后到底色不透明;整体透明度仍按用户设置保留,文字与底色都会被桌面冲淡, + /// 所以最终只能选择最差端点对比度较高的黑/白,不能承诺一定达到目标。 + /// + public static AdaptiveTheme Resolve( + BackdropLuminance backdrop, + bool appThemeIsDark, + double surfaceOpacity = 1) + { + var opacity = NormalizeOpacity(surfaceOpacity); + 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, backdrop, opacity); + var bestContrast = WorstContrastAcrossBackdrop(theme, backdrop, opacity); + if (bestContrast >= MinimumContrastRatio) + return theme; + + // 整体透明度会同时淡化文字;各档都不达标时保留最差端点对比度最高的方案。 + var stronger = Build(isDark, ContrastGateSurfaceAlpha, backdrop, opacity); + var strongerContrast = WorstContrastAcrossBackdrop(stronger, backdrop, opacity); + if (strongerContrast >= MinimumContrastRatio) + return stronger; + if (strongerContrast > bestContrast) + { + theme = stronger; + bestContrast = strongerContrast; + } + + var opaqueSurface = Build(isDark, 1.0, backdrop, opacity); + return WorstContrastAcrossBackdrop(opaqueSurface, backdrop, opacity) >= bestContrast ? opaqueSurface : theme; + } + + /// + /// 按"合成之后的卡片底有多亮"选纯黑或纯白:这就是需求本身(浅底深字、深底白字), + /// 也保证了无论采样/透明度/主题怎么组合,字色都不会和眼睛看到的底色唱反调。 + /// + public static Color SelectForeground(double surfaceLuminance) => + SelectForeground(surfaceLuminance, surfaceLuminance); + + /// + /// 卡片底在两端的亮度并不相同( 到 + /// )时,取"最差那一端仍看得最清"的颜色。 + /// + public static Color SelectForeground(double darkestComposite, double lightestComposite) + { + var dark = NormalizeLuminance(darkestComposite); + var light = Math.Max(dark, NormalizeLuminance(lightestComposite)); + + // 不透明黑字在暗端最吃亏,不透明白字在亮端最吃亏。 + var blackWorst = ContrastRatio(dark, Colors.Black); + var whiteWorst = ContrastRatio(light, Colors.White); + return blackWorst >= whiteWorst ? Colors.Black : Colors.White; + } + + /// + /// 一个实色底盖在给定亮度的背景上之后的亮度: 是整块 + /// 卡片的不透明度, 是底色自身的透明度。 + /// + public static double ComposeSurfaceLuminance( + Color surface, + double surfaceAlpha, + double backdropLuminance, + double surfaceOpacity = 1) + { + var opacity = NormalizeOpacity(surfaceOpacity); + var alpha = NormalizeOpacity(surfaceAlpha) * opacity; + return Math.Clamp( + alpha * RelativeLuminance(surface) + (1 - alpha) * NormalizeLuminance(backdropLuminance), 0, 1); + } + + /// 中位数处可见文字与可见卡片底的对比度,包含整块卡片的不透明度。 + public static double ContrastAgainstSurface(AdaptiveTheme theme) => + ContrastRatio( + theme.SurfaceLuminance, + ComposeForegroundLuminance(theme.Foreground, theme.BackdropMedianLuminance, theme.SurfaceOpacity)); + + /// + /// 前景色在这张卡片上最差的那一处的对比度:卡片半透明时,背景的亮端与暗端会给出不同的 + /// 最终底色,两端都要达标才算真的看得清。 + /// + public static double WorstContrastAcrossBackdrop(AdaptiveTheme theme, BackdropLuminance backdrop) => + WorstContrastAcrossBackdrop(theme, backdrop, theme.SurfaceOpacity); + + public static double WorstContrastAcrossBackdrop( + AdaptiveTheme theme, + BackdropLuminance backdrop, + double surfaceOpacity) + { + var opacity = NormalizeOpacity(surfaceOpacity); + var darkest = ComposeSurfaceLuminance(theme.Surface, theme.SurfaceAlpha, backdrop.P10, opacity); + var lightest = ComposeSurfaceLuminance(theme.Surface, theme.SurfaceAlpha, backdrop.P90, opacity); + return Math.Min( + ContrastRatio(darkest, ComposeForegroundLuminance(theme.Foreground, backdrop.P10, opacity)), + ContrastRatio(lightest, ComposeForegroundLuminance(theme.Foreground, backdrop.P90, opacity))); + } + + /// WCAG 相对亮度(输入已经是 0–1 线性亮度)。 + public static double ContrastRatio(double backgroundLuminance, Color foreground) => + ContrastRatio(backgroundLuminance, RelativeLuminance(foreground)); + + private static double ContrastRatio(double backgroundLuminance, double foregroundLuminance) + { + var lighter = Math.Max(backgroundLuminance, foregroundLuminance); + var darker = Math.Min(backgroundLuminance, foregroundLuminance); + return (lighter + 0.05) / (darker + 0.05); + } + + private static double ComposeForegroundLuminance(Color foreground, double backdropLuminance, double surfaceOpacity) + { + var opacity = NormalizeOpacity(surfaceOpacity); + return opacity * RelativeLuminance(foreground) + (1 - opacity) * NormalizeLuminance(backdropLuminance); + } + + /// 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, + BackdropLuminance backdrop, + double surfaceOpacity = 1) + { + var surfaceBase = isDark ? DarkSurfaceColor : LightSurfaceColor; + + // 使用实际输出的 8 位 alpha 计算,确保选色和对比度检查针对同一块底色。 + var surface = WithAlpha(surfaceBase, (byte)Math.Round(alpha * 255)); + var composited = ComposeSurfaceLuminance(surface, surface.A / 255d, backdrop.Median, surfaceOpacity); + var theme = new AdaptiveTheme( + IsDarkBackdrop: isDark, + Foreground: Colors.Black, + SecondaryForeground: default, + Stroke: default, + Surface: surface, + CardSurface: WithAlpha(surfaceBase, (byte)Math.Round(Math.Min(1.0, alpha + CardSurfaceAlphaBonus) * 255)), + AvatarSurface: default, + SurfaceLuminance: composited) + { + SurfaceOpacity = NormalizeOpacity(surfaceOpacity), + BackdropMedianLuminance = NormalizeLuminance(backdrop.Median) + }; + + // 整体透明度同时作用在字和底上。比较两种可见字色在两个端点的最差对比度。 + var blackWorst = WorstContrastAcrossBackdrop(theme, backdrop, surfaceOpacity); + var whiteWorst = WorstContrastAcrossBackdrop(theme with { Foreground = Colors.White }, backdrop, surfaceOpacity); + var foreground = blackWorst >= whiteWorst ? Colors.Black : Colors.White; + return theme with + { + Foreground = foreground, + SecondaryForeground = WithAlpha(foreground, SecondaryAlpha), + Stroke = WithAlpha(foreground, StrokeAlpha), + AvatarSurface = WithAlpha(foreground, AvatarAlpha) + }; + } + + private static double NormalizeOpacity(double value) + { + if (double.IsNaN(value)) + return 1; + + return Math.Clamp(value, 0, 1); + } + + private static double NormalizeLuminance(double value) + { + if (double.IsNaN(value)) + return 0; + + return Math.Clamp(value, 0, 1); + } + + 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.Core/Services/Profiles/HistoryGroupScope.cs b/SecRandom.Core/Services/Profiles/HistoryGroupScope.cs index 5478be332..527a20e4d 100644 --- a/SecRandom.Core/Services/Profiles/HistoryGroupScope.cs +++ b/SecRandom.Core/Services/Profiles/HistoryGroupScope.cs @@ -53,4 +53,43 @@ public static HistoryGroupScope Resolve( ? new HistoryGroupScope(name, false) : new HistoryGroupScope(string.Empty, true); } + + /// + /// 解析「这条历史记录该盖哪个组标记」,与读取范围分开。 + /// + /// 该抽取通道自己保存的默认记录组(空串 = 默认记录组)。 + /// 当前档案里可用的组名; = 这次读不到。 + /// + /// 非空组名:空串 = 默认记录组,其余 = 该具名组。这个值**永远不为 **。 + /// + /// + /// + /// 与 的区别只有一条,但它是本质的:历史记录组总开关不参与。 + /// 开关管的是「界面上能不能临时切组」,不是「记录落在哪个组」。关掉开关只是不许临时切换, + /// 每个抽取模式仍然按**自己**保存的默认记录组落标记——否则点名、闪抽、抽奖、编排的记录会 + /// 一起挤进默认记录组,重新打开功能时就再也拆不回各自的组了。 + /// + /// + /// 读取范围仍然走 的三态:开关关掉时选择器不可见,用户看不到当前按哪批 + /// 历史算权重,所以读取退回「全部历史」;写入却必须保留归属,两者刻意不同。 + /// + /// + /// 目录这次读不到时返回配置里的名字而不是空串:把记录静默移进默认组是不可逆的信息丢失, + /// 而组名本身只是标记(组名是从记录里派生出来的),保留用户写下的名字才是可恢复的那一侧。 + /// 名字已经不存在时才回落到默认记录组——绝不写一个用户删掉的幽灵组名。 + /// + /// + public static string ResolveRecordGroup( + string? configuredGroup, + IReadOnlyList? availableGroupNames) + { + if (string.IsNullOrWhiteSpace(configuredGroup)) + return string.Empty; + + var name = configuredGroup.Trim(); + if (availableGroupNames is null) + return name; + + return availableGroupNames.Contains(name, StringComparer.Ordinal) ? name : string.Empty; + } } diff --git a/SecRandom.Core/Services/Profiles/ProfileCatalogManager.cs b/SecRandom.Core/Services/Profiles/ProfileCatalogManager.cs index d0b1758e5..0597da60b 100644 --- a/SecRandom.Core/Services/Profiles/ProfileCatalogManager.cs +++ b/SecRandom.Core/Services/Profiles/ProfileCatalogManager.cs @@ -66,9 +66,8 @@ public bool DeleteStudentList(string name, bool deleteHistory) if (string.Equals(profileService.StudentListConfig?.Name, name, StringComparison.Ordinal)) { - var nextName = GetStudentListNames().FirstOrDefault(); - if (nextName is not null) - profileService.LoadStudentProfile(nextName, saveCurrent: false); + // 删掉的正好是活动名单:有下一份就切过去,没有就把活动档案真正清空(删除最后一份名单是合法的)。 + profileService.LoadStudentProfile(GetStudentListNames().FirstOrDefault() ?? string.Empty, saveCurrent: false); } logger.LogInformation("已删除点名名单:名单={ListName},连带历史={DeleteHistory}。", name, deleteHistory); @@ -86,9 +85,8 @@ public bool DeletePrizeList(string name, bool deleteHistory) if (string.Equals(profileService.PrizeListConfig?.Name, name, StringComparison.Ordinal)) { - var nextName = GetPrizeListNames().FirstOrDefault(); - if (nextName is not null) - profileService.LoadPrizeProfile(nextName, saveCurrent: false); + // 与 DeleteStudentList 同理:没有剩余奖品池时清空活动档案,而不是继续指向已删除的文件。 + profileService.LoadPrizeProfile(GetPrizeListNames().FirstOrDefault() ?? string.Empty, saveCurrent: false); } logger.LogInformation("已删除奖品池:奖品池={ListName},连带历史={DeleteHistory}。", name, deleteHistory); @@ -207,19 +205,23 @@ public bool ReplacePrizes(string name, IReadOnlyList prizes) public void SetDefaultStudentList(string name) { - if (string.IsNullOrWhiteSpace(name) || configHandler.Data.RollCallSettings.DefaultClass == name) + // 空名字代表"没有默认名单":删掉最后一份名单后必须能把默认设置真正清掉, + // 否则重启会留下一个指向已删除名单的默认值。 + var normalized = string.IsNullOrWhiteSpace(name) ? string.Empty : name; + if (configHandler.Data.RollCallSettings.DefaultClass == normalized) return; - configHandler.Data.RollCallSettings.DefaultClass = name; + configHandler.Data.RollCallSettings.DefaultClass = normalized; configHandler.Save(); } public void SetDefaultPrizePool(string name) { - if (string.IsNullOrWhiteSpace(name) || configHandler.Data.LotterySettings.DefaultPool == name) + var normalized = string.IsNullOrWhiteSpace(name) ? string.Empty : name; + if (configHandler.Data.LotterySettings.DefaultPool == normalized) return; - configHandler.Data.LotterySettings.DefaultPool = name; + configHandler.Data.LotterySettings.DefaultPool = normalized; configHandler.Save(); } @@ -278,14 +280,16 @@ public bool ClearPrizeHistory(string name) public int MoveStudentHistoryGroup( string profileName, IReadOnlyCollection recordIds, - string targetGroup) => - MoveHistoryGroup(HistoryGroupKind.RollCall, profileName, recordIds, targetGroup); + string targetGroup, + string? sourceGroup = null) => + MoveHistoryGroup(HistoryGroupKind.RollCall, profileName, recordIds, targetGroup, sourceGroup); public int MovePrizeHistoryGroup( string profileName, IReadOnlyCollection recordIds, - string targetGroup) => - MoveHistoryGroup(HistoryGroupKind.Lottery, profileName, recordIds, targetGroup); + string targetGroup, + string? sourceGroup = null) => + MoveHistoryGroup(HistoryGroupKind.Lottery, profileName, recordIds, targetGroup, sourceGroup); /// /// Re-marks the given records of one profile's history file as belonging to . @@ -299,6 +303,13 @@ public int MovePrizeHistoryGroup( /// regrouping operation rewrite the draw weights it is supposed to be orthogonal to. /// /// + /// A group filter narrows the move. is the record group the caller's + /// view is currently filtered to ( = no filter). Passing it keeps the operation + /// consistent with what the user selected: moving a member whose records are spread across several groups + /// must not silently drag the group they are not looking at along. Without a filter every record of the + /// named members moves, which is the pre-filter behaviour. + /// + /// /// One file, saved once, and only when something changed. The save goes through the profile's own /// history handler ( / /// → the atomic temp-file-and-replace write in FileConfigService), exactly like @@ -318,7 +329,8 @@ private int MoveHistoryGroup( HistoryGroupKind kind, string profileName, IReadOnlyCollection recordIds, - string targetGroup) + string targetGroup, + string? sourceGroup) { ArgumentNullException.ThrowIfNull(recordIds); // 档案名会参与拼路径:非法名字在这里就以 ArgumentException 拒绝,绝不落到不安全的路径拼接上。 @@ -346,7 +358,7 @@ private int MoveHistoryGroup( if (view is null) throw new InvalidOperationException(HistoryGroupName.ErrorProfileUnavailable); - var moved = MoveIntoGroup(view.Records, ids, target); + var moved = MoveIntoGroup(view.Records, ids, target, sourceGroup); if (moved == 0) return 0; @@ -449,7 +461,8 @@ private sealed record HistoryView( private static int MoveIntoGroup( ObservableDictionary records, HashSet recordIds, - string target) + string target, + string? sourceGroup) { var moved = 0; foreach (var pair in records) @@ -459,6 +472,12 @@ private static int MoveIntoGroup( foreach (var item in pair.Value.Histories) { + // 视图按某个组过滤时,移动只能改这个组里的记录;否则用户没看见的其它组的记录 + // 会一起被拖走,选中行与实际改动就对不上了。 + if (sourceGroup is not null + && !string.Equals(item.HistoryGroup ?? string.Empty, sourceGroup, StringComparison.Ordinal)) + continue; + if (string.Equals(item.HistoryGroup ?? string.Empty, target, StringComparison.Ordinal)) continue; diff --git a/SecRandom.Core/Services/Profiles/ProfileSequenceNumbering.cs b/SecRandom.Core/Services/Profiles/ProfileSequenceNumbering.cs index 9a0d8d8df..1de9cb4d9 100644 --- a/SecRandom.Core/Services/Profiles/ProfileSequenceNumbering.cs +++ b/SecRandom.Core/Services/Profiles/ProfileSequenceNumbering.cs @@ -27,6 +27,28 @@ public enum SequenceNumberConflictKind /// 一名成员的编号顺延计划项; 指向原集合下标。 public sealed record SequenceNumberShiftEntry(int Index, string OldId, long OldNumber, long NewNumber); +/// +/// 删除单个成员时的编号前移分析结果。只有被删成员使用纯数字编号、没有其他成员使用同一编号、 +/// 且后面确实还有更大的数字编号时,才允许前移。 +/// +public sealed class SequenceNumberRemoval +{ + /// 被删成员在原集合中的下标;下标无效时为 -1。 + public int RemovedIndex { get; init; } = -1; + + /// 被删成员去掉首尾空白后的编号。 + public string RemovedId { get; init; } = string.Empty; + + /// 被删成员的纯数字编号;不是纯数字时为 null。 + public long? RemovedNumber { get; init; } + + /// 是否可以把后面的数字编号整体向前移动一位。 + public bool CanShift { get; init; } + + /// 会被前移的成员及前移结果,按原集合顺序; 为 false 时为空。 + public IReadOnlyList ShiftEntries { get; init; } = []; +} + /// 新增成员时的编号冲突分析结果,供页面决定展示哪种确认弹窗。 public sealed class SequenceNumberConflict { @@ -157,4 +179,54 @@ public static SequenceNumberConflict Analyze(IReadOnlyList? existingIds, AppendNumber = appendNumber }; } + + /// 分析删除 处的成员时,后面的数字编号能否整体向前移动一位。 + /// + /// 只有被删成员本身是纯数字编号时才谈得上前移;另外还有成员使用同一编号时也必须放弃, + /// 因为前移会把更大的编号搬到被删编号上,形成新的重复。前移只改显示编号, + /// 成员身份仍由 RecordId 承担,抽取历史、临时记录与公平权重都不受影响。 + /// + public static SequenceNumberRemoval AnalyzeRemoval(IReadOnlyList? existingIds, int removedIndex) + { + if (existingIds is null || removedIndex < 0 || removedIndex >= existingIds.Count) + return new SequenceNumberRemoval { RemovedIndex = removedIndex }; + + var removedId = existingIds[removedIndex]?.Trim() ?? string.Empty; + if (TryParseNumber(removedId) is not { } removedNumber) + return new SequenceNumberRemoval { RemovedIndex = removedIndex, RemovedId = removedId }; + + var shiftEntries = new List(); + for (var index = 0; index < existingIds.Count; index++) + { + if (index == removedIndex) + continue; + + var id = existingIds[index]?.Trim() ?? string.Empty; + if (TryParseNumber(id) is not { } number) + continue; + + // 另有同号成员:前移会把这个编号再写一遍,因此不能前移。 + if (number == removedNumber) + return new SequenceNumberRemoval + { + RemovedIndex = removedIndex, + RemovedId = removedId, + RemovedNumber = removedNumber + }; + + if (number < removedNumber) + continue; + + shiftEntries.Add(new SequenceNumberShiftEntry(index, id, number, number - 1)); + } + + return new SequenceNumberRemoval + { + RemovedIndex = removedIndex, + RemovedId = removedId, + RemovedNumber = removedNumber, + CanShift = shiftEntries.Count > 0, + ShiftEntries = shiftEntries + }; + } } diff --git a/SecRandom.Core/Services/Profiles/ProfileService.cs b/SecRandom.Core/Services/Profiles/ProfileService.cs index a12c58465..ca636a138 100644 --- a/SecRandom.Core/Services/Profiles/ProfileService.cs +++ b/SecRandom.Core/Services/Profiles/ProfileService.cs @@ -28,6 +28,8 @@ public ProfileService( _configHandler = configHandler; _configService = configService; + SeedDefaultListsOnFirstRun(); + var studentListName = ResolveProfileName("list", "roll_call_list", _configHandler.Data.RollCallSettings.DefaultClass); var prizeListName = ResolveProfileName("list", "lottery_list", _configHandler.Data.LotterySettings.DefaultPool); @@ -38,9 +40,9 @@ public ProfileService( _logger.LogInformation( "已加载默认档案:学生名单={StudentListName},学生数量={StudentCount},奖品池={PrizeListName},奖品数量={PrizeCount}。", - StudentListConfig.Name, + StudentListConfig?.Name ?? NoListName, CurrentStudentList?.Students.Count ?? 0, - PrizeListConfig.Name, + PrizeListConfig?.Name ?? NoListName, CurrentPrizeList?.Prizes.Count ?? 0); } @@ -56,8 +58,14 @@ public ProfileService( public void LoadStudentProfile(string name, bool saveCurrent = true) { - if (name == string.Empty) + // 空名不是"什么都不做",而是"当前没有名单":删掉最后一份名单后必须真的把活动档案清空, + // 否则内存里还留着已删除的名单,随后任何一次保存都会把它写回磁盘。 + if (string.IsNullOrWhiteSpace(name)) + { + ClearStudentProfile(saveCurrent); return; + } + ProfileConfigBase.ValidateProfileName(name); if (StudentListConfig?.Name == name && StudentHistoryConfig?.Name == name) @@ -84,8 +92,13 @@ public void LoadStudentProfile(string name, bool saveCurrent = true) public void LoadPrizeProfile(string name, bool saveCurrent = true) { - if (name == string.Empty) + // 与 LoadStudentProfile 同理:空名代表"当前没有奖品池",必须清空而不是保留旧档案。 + if (string.IsNullOrWhiteSpace(name)) + { + ClearPrizeProfile(saveCurrent); return; + } + ProfileConfigBase.ValidateProfileName(name); if (PrizeListConfig?.Name == name && PrizeHistoryConfig?.Name == name) @@ -360,12 +373,84 @@ public void RestorePrizeHistorySnapshot(string snapshotJson) PrizeHistoryConfig?.Save(); } - private StudentListConfig CreateStudentListConfig(string name) => new(name, _logger, _configService); - private StudentHistoryConfig CreateStudentHistoryConfig(string name) => new(name, _logger, _configService); - private PrizeListConfig CreatePrizeListConfig(string name) => new(name, _logger, _configService); - private PrizeHistoryConfig CreatePrizeHistoryConfig(string name) => new(name, _logger, _configService); + private const string NoListName = "(无名单)"; + + private StudentListConfig? CreateStudentListConfig(string? name) => + string.IsNullOrWhiteSpace(name) ? null : new StudentListConfig(name, _logger, _configService); + + private StudentHistoryConfig? CreateStudentHistoryConfig(string? name) => + string.IsNullOrWhiteSpace(name) ? null : new StudentHistoryConfig(name, _logger, _configService); + + private PrizeListConfig? CreatePrizeListConfig(string? name) => + string.IsNullOrWhiteSpace(name) ? null : new PrizeListConfig(name, _logger, _configService); + + private PrizeHistoryConfig? CreatePrizeHistoryConfig(string? name) => + string.IsNullOrWhiteSpace(name) ? null : new PrizeHistoryConfig(name, _logger, _configService); + + /// + /// Detaches the active roll-call profile: after the last list is deleted there is no profile to save, record or + /// reload, so every consumer must see instead of a leftover (already deleted) file. + /// + private void ClearStudentProfile(bool saveCurrent) + { + if (StudentListConfig is null && StudentHistoryConfig is null) + return; + + if (saveCurrent) + { + StudentListConfig?.Save(); + StudentHistoryConfig?.Save(); + } + + StudentListConfig = null; + StudentHistoryConfig = null; + _logger.LogInformation("已清空当前点名名单档案:现在没有名单。"); + } - private static string ResolveProfileName(string rootA, string rootB, string preferredName) + /// Detaches the active prize pool for the same reason as . + private void ClearPrizeProfile(bool saveCurrent) + { + if (PrizeListConfig is null && PrizeHistoryConfig is null) + return; + + if (saveCurrent) + { + PrizeListConfig?.Save(); + PrizeHistoryConfig?.Save(); + } + + PrizeListConfig = null; + PrizeHistoryConfig = null; + _logger.LogInformation("已清空当前奖品池档案:现在没有奖品池。"); + } + + /// + /// A first run (guide not completed yet) gets one blank default list per channel, which is what every + /// build up to now produced implicitly at startup. + /// + /// + /// It only ever happens before the guide completes, because after that deleting the last list has to mean + /// "there are no lists": recreating default on every restart would make the empty state impossible. + /// + private void SeedDefaultListsOnFirstRun() + { + if (_configHandler.Data.General.Basic.GuideCompleted) + return; + + if (!HasListFiles("roll_call_list")) + new StudentListConfig("default", _logger, _configService).Save(); + + if (!HasListFiles("lottery_list")) + new PrizeListConfig("default", _logger, _configService).Save(); + } + + private static bool HasListFiles(string directory) + { + var path = Utils.GetDirectoryPath("list", directory); + return Directory.Exists(path) && Directory.GetFiles(path, "*.json").Length > 0; + } + + private static string? ResolveProfileName(string rootA, string rootB, string preferredName) { // 「不使用名单」不是真实档案名:回落到磁盘上已有的名单,绝不为哨兵创建/读取档案文件。 if (RosterSelection.IsNone(preferredName)) @@ -382,11 +467,11 @@ private static string ResolveProfileName(string rootA, string rootB, string pref return preferredName; } - var existing = Directory.GetFiles(directory, "*.json") + // 目录里没有任何名单文件就是"没有名单":不再回落到 default,否则删掉最后一份名单后重启会被凭空重建, + // 而"至少保留一份名单"的限制正是靠这条回落才显得存在。 + return Directory.GetFiles(directory, "*.json") .Select(Path.GetFileNameWithoutExtension) .FirstOrDefault(ProfileConfigBase.IsValidProfileName); - - return string.IsNullOrWhiteSpace(existing) ? "default" : existing; } } } diff --git a/SecRandom.Core/Services/SimpleMode/SimpleModeDefaults.cs b/SecRandom.Core/Services/SimpleMode/SimpleModeDefaults.cs index c54b2dd1b..1dfc3d109 100644 --- a/SecRandom.Core/Services/SimpleMode/SimpleModeDefaults.cs +++ b/SecRandom.Core/Services/SimpleMode/SimpleModeDefaults.cs @@ -67,6 +67,9 @@ public static class SimpleModeDefaults /// 简洁模式下抽奖设置使用的默认值。 public static LotterySettingsConfig LotterySettings => Model.LotterySettings; + /// 简洁模式下随机数抽取使用的默认值。 + public static RandomNumberSettingsConfig RandomNumberSettings => Model.RandomNumberSettings; + /// 简洁模式下抽取设置使用的默认「公平抽取设置」。 public static FairDrawSettingsConfig FairDrawSettings => Model.FairDrawSettings; diff --git a/SecRandom.Core/Services/SingleInstance/SingleInstanceService.cs b/SecRandom.Core/Services/SingleInstance/SingleInstanceService.cs index c027773b5..665119563 100644 --- a/SecRandom.Core/Services/SingleInstance/SingleInstanceService.cs +++ b/SecRandom.Core/Services/SingleInstance/SingleInstanceService.cs @@ -24,9 +24,12 @@ public sealed class SingleInstanceService : IDisposable private const string AppId = "SecRandom_3F2A1B0E"; private const string MutexName = $"SecRandom_SingleInstance_{AppId}"; public const string IpcPipeName = $"SecRandom_IPC_{AppId}"; + public const string EventPipeName = $"SecRandom_IPC_Events_{AppId}"; private static readonly TimeSpan FrameReadTimeout = TimeSpan.FromSeconds(5); private static readonly TimeSpan ResponseReadTimeout = TimeSpan.FromSeconds(30); private const int MaxConcurrentConnections = 8; + /// v2 allows a whole roster in one frame; v1 stays capped by its 8 KB parser. + public const int MaxAutomationFrameLength = 256 * 1024; private static readonly UTF8Encoding StrictUtf8 = new(false, true); private Mutex? _mutex; @@ -59,6 +62,12 @@ public static SingleInstanceService Instance /// public event Action? CommandReceived; public event Func>? RequestReceived; + /// + /// v2 automation frame handler. Receives the raw one-line JSON envelope and returns + /// the raw one-line response (already serialized), so the Core transport stays + /// independent of the app-layer command registry. + /// + public event Func>? AutomationRequestReceived; private static readonly JsonSerializerOptions IpcJsonOptions = new(JsonSerializerDefaults.Web); @@ -227,7 +236,7 @@ private async Task HandleAcceptedConnectionAsync(NamedPipeServerStream server, C private static async Task ReadRequestLineAsync(StreamReader reader, CancellationToken cancellationToken) { - var buffer = new char[ProtocolRequestParser.MaxRequestLength + 1]; + var buffer = new char[MaxAutomationFrameLength + 1]; var length = 0; while (length < buffer.Length) { @@ -280,6 +289,58 @@ await WriteResponseAsync(writer, return; } + if (TryReadFrameVersion(frame, out var frameVersion, out var frameType)) + { + if (frameVersion == 2 && + (string.Equals(frameType, "rpc", StringComparison.Ordinal) || + string.Equals(frameType, "hello", StringComparison.Ordinal))) + { + var automationHandler = AutomationRequestReceived; + if (automationHandler is null) + { + await WriteAutomationLineAsync(writer, IpcV2ResponseEnvelope.Failure( + null, + IpcV2ErrorEnvelope.Create( + AutomationErrorCodes.PipeUnavailable, + "SecRandom 尚未准备好处理 IPC 请求。", + retryable: true))).ConfigureAwait(false); + return; + } + + string? automationResponse; + try + { + automationResponse = await automationHandler(frame, cancellationToken).ConfigureAwait(false); + } + catch + { + automationResponse = null; + } + + if (string.IsNullOrWhiteSpace(automationResponse)) + { + await WriteAutomationLineAsync(writer, IpcV2ResponseEnvelope.Failure( + null, + IpcV2ErrorEnvelope.Create( + AutomationErrorCodes.InternalError, + "IPC 请求处理失败。", + retryable: true))).ConfigureAwait(false); + return; + } + + await writer.WriteLineAsync(automationResponse).ConfigureAwait(false); + await writer.FlushAsync().ConfigureAwait(false); + return; + } + } + + if (frame.Length > ProtocolRequestParser.MaxRequestLength) + { + await WriteResponseAsync(writer, + IpcResponseEnvelope.TransportFailure("unknown", "invalid_request", "IPC 请求超出长度限制。")).ConfigureAwait(false); + return; + } + IpcRequestEnvelope? request; try { @@ -321,6 +382,35 @@ await WriteResponseAsync(writer, await WriteResponseAsync(writer, response).ConfigureAwait(false); } + private static bool TryReadFrameVersion(string frame, out int version, out string? type) + { + version = 0; + type = null; + try + { + using var document = JsonDocument.Parse(frame); + if (document.RootElement.ValueKind != JsonValueKind.Object) + return false; + + if (document.RootElement.TryGetProperty("version", out var versionElement)) + versionElement.TryGetInt32(out version); + if (document.RootElement.TryGetProperty("type", out var typeElement) && + typeElement.ValueKind == JsonValueKind.String) + type = typeElement.GetString(); + return true; + } + catch (JsonException) + { + return false; + } + } + + private static async Task WriteAutomationLineAsync(StreamWriter writer, IpcV2ResponseEnvelope response) + { + await writer.WriteLineAsync(JsonSerializer.Serialize(response, IpcJsonOptions)).ConfigureAwait(false); + await writer.FlushAsync().ConfigureAwait(false); + } + private static async Task WriteResponseAsync(StreamWriter writer, IpcResponseEnvelope response) { await writer.WriteLineAsync(JsonSerializer.Serialize(response, IpcJsonOptions)).ConfigureAwait(false); diff --git a/SecRandom.Core/Services/Stats/RandomNumberStatisticsService.cs b/SecRandom.Core/Services/Stats/RandomNumberStatisticsService.cs new file mode 100644 index 000000000..52a7c3b6a --- /dev/null +++ b/SecRandom.Core/Services/Stats/RandomNumberStatisticsService.cs @@ -0,0 +1,308 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text.Json; +using Microsoft.Extensions.Logging; +using SecRandom.Core.Abstraction; +using SecRandom.Shared; + +namespace SecRandom.Core.Services.Stats; + +/// One committed number-range draw kept for the overview and the random-number settings page. +public sealed class RandomNumberDrawRecord +{ + public DateTime DrawTime { get; set; } + public string Source { get; set; } = string.Empty; + public int RangeStart { get; set; } + public int RangeEnd { get; set; } + public int Count { get; set; } + public List Numbers { get; set; } = []; +} + +/// Lifetime draw count for one configured number range. +public sealed class RandomNumberRangeStatistics +{ + public int RangeStart { get; set; } + public int RangeEnd { get; set; } + public int DrawCount { get; set; } + public DateTime? LastDrawAt { get; set; } +} + +/// Persisted random-number statistics document. +public sealed class RandomNumberStatistics +{ + public const string CurrentFormat = "SecRandomRandomNumberStats/v1"; + public const int MaxRecentRecords = 100; + + public string Format { get; set; } = CurrentFormat; + public int TotalRounds { get; set; } + public int TotalDrawnCount { get; set; } + public DateTime? LastDrawAt { get; set; } + public List Ranges { get; set; } = []; + public List Recent { get; set; } = []; +} + +/// Immutable view of the random-number statistics for presentation code. +public sealed record RandomNumberStatisticsSnapshot( + int TotalRounds, + int TotalDrawnCount, + DateTime? LastDrawAt, + IReadOnlyList Ranges, + IReadOnlyList Recent); + +/// +/// Owns the random-number statistics file. Number draws deliberately never write roster history, so this +/// small document is the only durable record of them; it is also the overview page's only data source for +/// that mode. +/// +public interface IRandomNumberStatisticsService +{ + RandomNumberStatisticsSnapshot Load(); + void Record(string source, int rangeStart, int rangeEnd, IReadOnlyList numbers); + void Clear(); + event EventHandler? Changed; +} + +/// +/// Atomic JSON store for . A draw is best-effort: a statistics write +/// failure must never surface to the draw that has already committed. +/// +public sealed class RandomNumberStatisticsService : IRandomNumberStatisticsService +{ + private readonly ILogger _logger; + private readonly string _filePath; + private readonly object _gate = new(); + + public RandomNumberStatisticsService(ILogger logger) + : this(logger, Utils.GetFilePath("history", "random-number", "stats.json")) + { + } + + /// Test seam: lets a test point at a temporary file instead of the data root. + public RandomNumberStatisticsService(ILogger logger, string filePath) + { + _logger = logger; + _filePath = filePath; + } + + public event EventHandler? Changed; + + public RandomNumberStatisticsSnapshot Load() + { + lock (_gate) + return ToSnapshot(LoadDocument()); + } + + public void Record(string source, int rangeStart, int rangeEnd, IReadOnlyList numbers) + { + if (numbers.Count == 0) + return; + + lock (_gate) + { + try + { + var document = LoadDocument(); + var drawTime = DateTime.Now; + document.TotalRounds++; + document.TotalDrawnCount += numbers.Count; + document.LastDrawAt = drawTime; + + var range = document.Ranges.FirstOrDefault(item => + item.RangeStart == rangeStart && item.RangeEnd == rangeEnd); + if (range is null) + { + range = new RandomNumberRangeStatistics + { + RangeStart = rangeStart, + RangeEnd = rangeEnd + }; + document.Ranges.Add(range); + } + + range.DrawCount++; + range.LastDrawAt = drawTime; + + document.Recent.InsertRange(0, + [ + new RandomNumberDrawRecord + { + DrawTime = drawTime, + Source = source, + RangeStart = rangeStart, + RangeEnd = rangeEnd, + Count = numbers.Count, + Numbers = [.. numbers] + } + ]); + if (document.Recent.Count > RandomNumberStatistics.MaxRecentRecords) + document.Recent.RemoveRange(RandomNumberStatistics.MaxRecentRecords, + document.Recent.Count - RandomNumberStatistics.MaxRecentRecords); + + Save(document); + Changed?.Invoke(this, EventArgs.Empty); + } + catch (Exception exception) + { + _logger.LogWarning(exception, "随机数抽取已提交,但随机数统计写入失败。"); + } + } + } + + public void Clear() + { + lock (_gate) + { + try + { + Save(new RandomNumberStatistics()); + Changed?.Invoke(this, EventArgs.Empty); + } + catch (Exception exception) + { + _logger.LogWarning(exception, "清除随机数统计失败。"); + } + } + } + + private RandomNumberStatistics LoadDocument() + { + if (!File.Exists(_filePath)) + return new RandomNumberStatistics(); + + try + { + var document = JsonSerializer.Deserialize( + File.ReadAllText(_filePath), ConfigServiceBase.JsonOptions); + if (document is null + || !string.Equals(document.Format, RandomNumberStatistics.CurrentFormat, StringComparison.Ordinal)) + throw new InvalidDataException("Unsupported random-number statistics format."); + + document.TotalRounds = Math.Max(0, document.TotalRounds); + document.TotalDrawnCount = Math.Max(0, document.TotalDrawnCount); + document.Recent ??= []; + document.Recent = document.Recent + .Where(record => record is not null) + .Take(RandomNumberStatistics.MaxRecentRecords) + .ToList(); + document.Ranges = NormalizeRanges(document.Ranges, document.Recent); + return document; + } + catch (Exception exception) when (exception is not OutOfMemoryException) + { + _logger.LogWarning(exception, "随机数统计文件不可读,已隔离并重新开始:{Path}", _filePath); + TryQuarantine(); + return new RandomNumberStatistics(); + } + } + + private static List NormalizeRanges( + List? stored, + IReadOnlyList recent) + { + var ranges = new Dictionary<(int Start, int End), RandomNumberRangeStatistics>(); + foreach (var item in stored ?? []) + { + if (item is null || item.RangeEnd < item.RangeStart || item.DrawCount <= 0) + continue; + + var key = (item.RangeStart, item.RangeEnd); + if (!ranges.TryGetValue(key, out var range)) + { + ranges[key] = range = new RandomNumberRangeStatistics + { + RangeStart = item.RangeStart, + RangeEnd = item.RangeEnd + }; + } + + range.DrawCount += item.DrawCount; + if (item.LastDrawAt is { } lastDrawAt + && (range.LastDrawAt is null || lastDrawAt > range.LastDrawAt)) + range.LastDrawAt = lastDrawAt; + } + + // Older documents predate per-range counters; their bounded recent list is the best available summary. + if (ranges.Count == 0) + { + foreach (var record in recent) + { + if (record.RangeEnd < record.RangeStart) + continue; + + var key = (record.RangeStart, record.RangeEnd); + if (!ranges.TryGetValue(key, out var range)) + { + ranges[key] = range = new RandomNumberRangeStatistics + { + RangeStart = record.RangeStart, + RangeEnd = record.RangeEnd + }; + } + + range.DrawCount++; + if (range.LastDrawAt is null || record.DrawTime > range.LastDrawAt) + range.LastDrawAt = record.DrawTime; + } + } + + return ranges.Values + .OrderBy(item => item.RangeStart) + .ThenBy(item => item.RangeEnd) + .ToList(); + } + + private void TryQuarantine() + { + try + { + if (File.Exists(_filePath)) + File.Move(_filePath, _filePath + ".corrupt", overwrite: true); + } + catch (Exception exception) + { + _logger.LogWarning(exception, "无法隔离损坏的随机数统计文件:{Path}", _filePath); + } + } + + private void Save(RandomNumberStatistics document) + { + var directory = Path.GetDirectoryName(_filePath); + if (!string.IsNullOrEmpty(directory)) + Directory.CreateDirectory(directory); + + var temporaryPath = $"{_filePath}.{Guid.NewGuid():N}.tmp"; + File.WriteAllText(temporaryPath, + JsonSerializer.Serialize(document, ConfigServiceBase.JsonOptions)); + File.Move(temporaryPath, _filePath, overwrite: true); + } + + private static RandomNumberStatisticsSnapshot ToSnapshot(RandomNumberStatistics document) => + new( + document.TotalRounds, + document.TotalDrawnCount, + document.LastDrawAt, + document.Ranges.Select(Clone).ToArray(), + document.Recent.Select(Clone).ToArray()); + + private static RandomNumberRangeStatistics Clone(RandomNumberRangeStatistics range) => + new() + { + RangeStart = range.RangeStart, + RangeEnd = range.RangeEnd, + DrawCount = range.DrawCount, + LastDrawAt = range.LastDrawAt + }; + + private static RandomNumberDrawRecord Clone(RandomNumberDrawRecord record) => + new() + { + DrawTime = record.DrawTime, + Source = record.Source, + RangeStart = record.RangeStart, + RangeEnd = record.RangeEnd, + Count = record.Count, + Numbers = [.. record.Numbers] + }; +} \ No newline at end of file diff --git a/SecRandom.Core/Services/Verification/ManagedVerificationKernel.cs b/SecRandom.Core/Services/Verification/ManagedVerificationKernel.cs index d93aea961..ceb91bf26 100644 --- a/SecRandom.Core/Services/Verification/ManagedVerificationKernel.cs +++ b/SecRandom.Core/Services/Verification/ManagedVerificationKernel.cs @@ -23,6 +23,28 @@ public VerificationKernelResult Draw(VerificationDrawInput input, ReadOnlySpan candidate.IsGuaranteed || candidate.WeightMicros != 1_000_000)) throw new InvalidOperationException("Inventory permutation requires equally weighted, unrestricted tickets."); + // An orchestrated draw commits the order itself: each drawn candidate carries its 1-based position in the + // round's arranged order in the weight slot, so the replay returns exactly those candidates in exactly + // that order and consumes no random material. A sparse or duplicated position is a malformed commitment, + // not something to paper over by sampling. + if (input.SamplingMode == VerificationSamplingMode.SequentialOrder) + { + var ordered = candidates + .Where(candidate => candidate.WeightMicros > 0) + .OrderBy(candidate => candidate.WeightMicros) + .ToList(); + var dense = ordered.Count == input.Count && !candidates.Any(candidate => candidate.IsGuaranteed); + for (var index = 0; dense && index < ordered.Count; index++) + dense = ordered[index].WeightMicros == index + 1; + if (!dense) + throw new InvalidOperationException("Orchestrated draws require a dense, unique committed order."); + + return new VerificationKernelResult + { + Winners = ordered.Select(candidate => new VerificationWinner(candidate.RecordId, candidate.OccurrenceIndex)).ToList() + }; + } + var guaranteed = candidates.Where(candidate => candidate.IsGuaranteed).ToList(); var winners = new List(input.Count); var random = new VerificationChaCha20Random(seed); diff --git a/SecRandom.Core/Services/Verification/VerificationWireCodec.cs b/SecRandom.Core/Services/Verification/VerificationWireCodec.cs index 4bb6dfb5c..dd808d39f 100644 --- a/SecRandom.Core/Services/Verification/VerificationWireCodec.cs +++ b/SecRandom.Core/Services/Verification/VerificationWireCodec.cs @@ -17,6 +17,7 @@ public static class VerificationWireCodec public const string InventoryLotteryAlgorithmId = "secrandom-inventory-permutation-chacha20/v3"; public const string WeightedLotteryAlgorithmId = "secrandom-lottery-weighted-without-replacement-chacha20/v3"; public const string NumberAlgorithmId = "secrandom-number-permutation-chacha20/v3"; + public const string OrchestratedSequenceAlgorithmId = "secrandom-orchestrated-sequential-order/v3"; public const string AlgorithmId = StudentAlgorithmId; /// @@ -40,6 +41,25 @@ public static class VerificationWireCodec /// public const string AlgorithmEngineVersion = "3.5.0"; + /// + /// Engine version that first understands orchestrated () + /// proofs. Only orchestrated proofs carry it. + /// + /// + /// The two families are versioned apart on purpose: an already deployed 3.5.0 verifier rejects any proof + /// stamped 3.6.0, so stamping ordinary draws with it would break every ordinary attestation until the + /// service ships 3.6. Orchestrated proofs cannot exist on a 3.5 verifier at all — it does not know + /// SequentialOrder or profiles 19/20 — so widening the version per sampling mode keeps the ordinary + /// channel working through the rollout and makes only the new mode wait for the service deployment. + /// + public const string OrchestratedAlgorithmEngineVersion = "3.6.0"; + + /// Engine version a proof of this sampling mode is stamped with. + public static string GetEngineVersion(VerificationSamplingMode samplingMode) => + samplingMode == VerificationSamplingMode.SequentialOrder + ? OrchestratedAlgorithmEngineVersion + : AlgorithmEngineVersion; + private static readonly byte[] InputMagic = "SRDI"u8.ToArray(); private static readonly byte[] RequestMagic = "SRDQ"u8.ToArray(); private static readonly byte[] ResponseMagic = "SRDR"u8.ToArray(); @@ -62,6 +82,7 @@ public static byte[] ComputeInputHash(VerificationDrawInput input) VerificationSamplingMode.HistoryBalancedWeighted => StudentAlgorithmId, VerificationSamplingMode.InventoryPermutation => InventoryLotteryAlgorithmId, VerificationSamplingMode.WeightedWithoutReplacement => WeightedLotteryAlgorithmId, + VerificationSamplingMode.SequentialOrder => OrchestratedSequenceAlgorithmId, _ => throw new ArgumentOutOfRangeException(nameof(samplingMode), samplingMode, "Verification sampling mode is unsupported.") }; @@ -85,6 +106,8 @@ public static byte[] ComputeInputHash(VerificationDrawInput input) VerificationAlgorithmProfile.StudentRandomInternalRuleNoRepeat => "secrandom-student-random-internal-rule-no-repeat/v3", VerificationAlgorithmProfile.StudentRandomInternalRuleHalfRepeat => "secrandom-student-random-internal-rule-half-repeat/v3", VerificationAlgorithmProfile.NumberUniformPermutation => NumberAlgorithmId, + VerificationAlgorithmProfile.StudentOrchestrated => "secrandom-student-orchestrated/v3", + VerificationAlgorithmProfile.LotteryOrchestrated => "secrandom-lottery-orchestrated/v3", _ => throw new ArgumentOutOfRangeException(nameof(profile), profile, "Verification algorithm profile is unsupported.") }; @@ -108,6 +131,8 @@ public static byte[] ComputeInputHash(VerificationDrawInput input) VerificationAlgorithmProfile.StudentRandomInternalRuleNoRepeat => "点名:随机,内幕规则加权,不重复", VerificationAlgorithmProfile.StudentRandomInternalRuleHalfRepeat => "点名:随机,内幕规则加权,半重复", VerificationAlgorithmProfile.NumberUniformPermutation => "数字:范围内等概率不放回", + VerificationAlgorithmProfile.StudentOrchestrated => "点名:编排抽取(顺序已事先排定)", + VerificationAlgorithmProfile.LotteryOrchestrated => "抽奖:编排抽取(顺序已事先排定)", _ => throw new ArgumentOutOfRangeException(nameof(profile), profile, "Verification algorithm profile is unsupported.") }; @@ -133,8 +158,11 @@ public static bool TryGetAlgorithmLabel(string algorithmId, out string label) "secrandom-student-random-internal-rule-no-repeat/v3" => GetAlgorithmLabel(VerificationAlgorithmProfile.StudentRandomInternalRuleNoRepeat), "secrandom-student-random-internal-rule-half-repeat/v3" => GetAlgorithmLabel(VerificationAlgorithmProfile.StudentRandomInternalRuleHalfRepeat), NumberAlgorithmId => GetAlgorithmLabel(VerificationAlgorithmProfile.NumberUniformPermutation), + "secrandom-student-orchestrated/v3" => GetAlgorithmLabel(VerificationAlgorithmProfile.StudentOrchestrated), + "secrandom-lottery-orchestrated/v3" => GetAlgorithmLabel(VerificationAlgorithmProfile.LotteryOrchestrated), InventoryLotteryAlgorithmId => "按剩余数量", WeightedLotteryAlgorithmId => "加权无放回", + OrchestratedSequenceAlgorithmId => "按预定顺序取出(不消耗随机数)", _ => string.Empty }; return !string.IsNullOrEmpty(label); @@ -167,6 +195,12 @@ or VerificationAlgorithmProfile.LotteryPanHalfRepeat VerificationAlgorithmProfile.LotteryInventoryCount or VerificationAlgorithmProfile.NumberUniformPermutation => samplingMode == VerificationSamplingMode.InventoryPermutation, + // An orchestrated draw replays from the committed positions alone, so it only accepts the sequential + // sampler: pairing it with a weighted or history sampler would let an arranged order replay as a + // random draw, which is exactly the claim this profile exists to prevent. + VerificationAlgorithmProfile.StudentOrchestrated + or VerificationAlgorithmProfile.LotteryOrchestrated + => samplingMode == VerificationSamplingMode.SequentialOrder, _ => false }; } @@ -196,6 +230,10 @@ or VerificationAlgorithmProfile.LotteryPanHalfRepeat => kind == VerificationDrawKind.Prize, VerificationAlgorithmProfile.NumberUniformPermutation => kind == VerificationDrawKind.Number, + VerificationAlgorithmProfile.StudentOrchestrated + => kind == VerificationDrawKind.Student, + VerificationAlgorithmProfile.LotteryOrchestrated + => kind == VerificationDrawKind.Prize, _ => false }; } diff --git a/SecRandom.Core/StylesBase.axaml b/SecRandom.Core/StylesBase.axaml index 72c3d2679..65c17d0f4 100644 --- a/SecRandom.Core/StylesBase.axaml +++ b/SecRandom.Core/StylesBase.axaml @@ -55,6 +55,8 @@ + + + + + - - /// - /// 为 true 时是"左右两侧显示"开启后出现在右边缘的副窗。副窗与主窗共用同一套按钮、 - /// 停靠与联动逻辑,但只保存自己的纵向锚点:横向位置永远由角色决定(主窗在左、副窗在右), - /// 不写共享的 ,否则两扇窗会互相覆盖位置。 + /// 为 true 时是"左右两侧显示"开启后补在另一侧的那扇窗;主窗则留在它原本所在的那一侧。 + /// 副窗与主窗共用同一套按钮、停靠与联动逻辑,但只保存自己的纵向锚点:横向位置永远由角色 + /// (主窗在哪侧、副窗就在另一侧)决定,不写共享的 , + /// 否则两扇窗会互相覆盖位置。 /// public FloatingWindow(bool isSecondary) { @@ -87,6 +120,8 @@ public FloatingWindow(bool isSecondary) DataContext = this; Position = new PixelPoint(ViewModel.Config.FloatPosition.X, ViewModel.Config.FloatPosition.Y); InitializeComponent(); + // 浮窗不用亚克力:窗口合成材质会沿整个矩形铺开、没有圆角,快选缩成"球 + 滑轨"那一小块时 + // 尤其突兀。这里固定走透明底,圆角与底色全部交给 WindowBorder 自己画。 TransparencyLevelHint = [WindowTransparencyLevel.Transparent]; this.ApplyPlatformFeatures(WindowFeatures.ToolWindow, enabled: true); ApplyFocusFreeMode(); @@ -106,13 +141,19 @@ public FloatingWindow(bool isSecondary) buttonRegistry.Changed += FloatingWindowButtonRegistry_OnChanged; Opened += OnOpened; PropertyChanged += OnWindowPropertyChanged; + SizeChanged += OnWindowSizeChanged; + if (Application.Current is { } application) + application.ActualThemeVariantChanged += OnActualThemeVariantChanged; Closed += (_, _) => { _isClosed = true; PropertyChanged -= OnWindowPropertyChanged; + SizeChanged -= OnWindowSizeChanged; _featureAvailability.Changed -= FeatureAvailabilityOnChanged; if (buttonRegistry is not null) buttonRegistry.Changed -= FloatingWindowButtonRegistry_OnChanged; + if (Application.Current is { } closedApplication) + closedApplication.ActualThemeVariantChanged -= OnActualThemeVariantChanged; }; var settings = EffectiveFloatingWindowSettings; @@ -125,14 +166,72 @@ private void FloatingWindowButtonRegistry_OnChanged(object? sender, EventArgs e) Dispatcher.UIThread.Post(RefreshItems); } + private void OnActualThemeVariantChanged(object? sender, EventArgs e) + { + // 卡片底是 DynamicResource 的实色画刷,主题切换由资源自己刷新;这里只需重算一次不透明度。 + ApplyWindowBorderBackdrop(EffectiveFloatingWindowSettings); + } + /// /// 窗口重新显示时补一次原生置顶:托盘"显示悬浮窗"、课程联动恢复、副窗创建都走 /// 而不是设置应用,不会经过 。 /// private void OnWindowPropertyChanged(object? sender, AvaloniaPropertyChangedEventArgs e) { - if (e.Property == IsVisibleProperty && IsVisible) + if (e.Property != IsVisibleProperty) + return; + + if (IsVisible) + { Dispatcher.UIThread.Post(ReassertNativeTopmost, DispatcherPriority.Render); + return; + } + + // 两侧同时显示时,一扇藏起来另一扇也得跟着藏,否则会剩半扇飘在桌面上。 + // 课程联动自己会同时藏两侧(它先把 _hiddenByCourseLinkage 置位再 Hide),这里不能抢跑, + // 否则另一侧的"联动前是否可见"会被记成 false,下课后就回不来了。 + // 关窗同理:Avalonia 先置 IsVisible = false 再触发 Closed,若把关闭当成收起,关掉副窗就会把 + // 留在原本那一侧的主窗一起藏掉(关掉"两侧同时显示"后两扇窗全不见了)。 + if (_hasBeenShown && !_isClosing && !_hiddenByCourseLinkage) + App.NotifyFloatingWindowHidden(this); + } + + /// + /// 另一侧被操作时把自己收成球:两侧同时显示时只留一侧展开,别让两扇窗一起抢注意力。 + /// + public void RequestAutoDock() + { + if (!IsVisible + || _isClosed + || _isDocked + || _isDockTransitioning + || _isMovingDockHandle + || _quickPickState != QuickPickState.Idle + || !EffectiveFloatingWindowSettings.StickToEdge) + return; + + _ = CollapseToDockAsync(); + } + + /// + /// 窗口高度变化后重新对齐两侧。按钮列表刚换好、语言/字号变化都会让 SizeToContent + /// 重新量一遍,量完的瞬间另一侧还停在旧锚点上,看起来就是"两扇窗高度不一样,拖一下才统一"。 + /// + private void OnWindowSizeChanged(object? sender, SizeChangedEventArgs e) + { + if (_isClosed || !IsLoaded) + return; + + // 快选期间窗口尺寸就是那块"球 + 滑轨"面板,和展开态没有可比性:这时候去对齐两侧, + // 会把正在快选的这扇窗按另一侧的锚点重新摆一次,用户看到的就是长按后浮窗上下抽搐。 + if (IsQuickPickActive) + return; + + var settings = EffectiveFloatingWindowSettings; + if (!settings.ShowOnBothSides || !settings.SyncBothSidesAnchor) + return; + + App.RequestFloatingWindowAnchorAlignment(); } public ViewModelBase ViewModel { get; } = IAppHost.GetService(); @@ -142,6 +241,38 @@ private void OnWindowPropertyChanged(object? sender, AvaloniaPropertyChangedEven public bool IsSecondary => _isSecondary; public bool IsEdgePinned => _edgePinned; + /// 快选面板(按住/滑选)是否正开着:这段时间窗口的尺寸和位置都属于面板,别人不能重摆。 + internal bool IsQuickPickActive => _quickPickState != QuickPickState.Idle; + + /// + /// 窗口此刻所在的横向半区: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 +301,9 @@ public int AnchorCenterY /// 是否钉边。 /// 钉在哪一侧;解除钉住时忽略。 /// - /// 钉边是"左右两侧显示"的交互约束:开启后主窗固定在右边缘、副窗固定在左边缘, + /// 钉边是"左右两侧显示"的交互约束:开启后主窗钉在它原本那一侧、副窗钉在另一侧, /// 用户只能纵向移动,不能被拖到屏幕中间或换到另一侧。解除钉住后恢复原来的吸附/自由拖动行为。 - /// 主窗固定在右侧,是因为关掉"左右两侧同时显示"后要保留的就是右侧那扇主窗。 + /// 主窗留在自己原本那一侧(而不是固定右侧),这样关掉"左右两侧同时显示"后窗口才回得到原来那一侧。 /// public void SetEdgePinned(bool pinned, bool onLeft) { @@ -207,6 +338,10 @@ public void ApplyUnifiedAnchor(int anchorCenterY) if (_isClosed) return; + // 快选把本窗挪到了指针旁边、尺寸也换成了面板:此时按锚点重新摆放会把面板从指针下拽走。 + if (IsQuickPickActive) + return; + var settings = EffectiveFloatingWindowSettings; if (!settings.ShowOnBothSides || !settings.SyncBothSidesAnchor) return; @@ -328,7 +463,7 @@ private static Button CreatePluginButton(FloatingWindowButtonDescriptor descript private void ApplyWindowSettings(FloatingWindowSettingsConfig settings) { - WindowBorder.Opacity = Math.Clamp(settings.FloatingWindowOpacity, 20, 100) / 100.0; + ApplyWindowBorderBackdrop(settings); // 顺序是刻意的:免激活样式要先落盘,因为平台层刷新扩展样式时会重新排一次 z 序; // 置顶必须最后写,否则会被随后的样式刷新抢回普通层。设置实时切换、简洁模式切换、 @@ -344,7 +479,6 @@ private void ApplyWindowSettings(FloatingWindowSettingsConfig settings) ? Orientation.Vertical : Orientation.Horizontal; ButtonsPanel.Width = double.NaN; - ApplyCustomText(settings, 0); if (!settings.StickToEdge && _isDocked) RestoreFromDock(); @@ -362,6 +496,19 @@ private void ApplyWindowSettings(FloatingWindowSettingsConfig settings) ReassertNativeTopmost(); } + /// + /// 卡片底:把"不透明度"设置直接压到 WindowBorder 上。 + /// + /// + /// 浮窗不再走窗口级亚克力(那层材质会沿整个矩形铺开、没有圆角),所以这里只有一条路径: + /// 由 WindowBorder 自己画半透明实色卡片,用户调多少就压多少。 + /// + private void ApplyWindowBorderBackdrop(FloatingWindowSettingsConfig settings) + { + var opacity = Math.Clamp(settings.FloatingWindowOpacity, 20, 100); + WindowBorder.Opacity = opacity / 100.0; + } + /// /// 应用"无焦点模式":开启后点击悬浮窗不会把焦点从前台应用(例如正在播放的 PPT)抢走, /// 翻页笔因此可以继续翻页。 @@ -532,6 +679,7 @@ private static Button GetRollCallButton(FloatingWindowSettingsConfig settings) private static Button GetQuickDrawButton(FloatingWindowSettingsConfig settings) { var b = CreateButton(FluentIcons.FlashFilled, Langs.Common.Resources.Feat_QuickDraw, settings); + b.Name = QuickDrawButtonName; b.Click += (sender, args) => { @@ -636,7 +784,6 @@ private void UpdateButtonsPanelWidth(FloatingWindowSettingsConfig settings) if (buttons.Length == 0) { ButtonsPanel.Width = double.NaN; - ApplyCustomText(settings, 0); return; } @@ -653,34 +800,6 @@ private void UpdateButtonsPanelWidth(FloatingWindowSettingsConfig settings) ButtonsPanel.Width = settings.FloatingWindowPlacement == 0 ? (buttonWidth + buttons[0].Margin.Left + buttons[0].Margin.Right) * rowCount : double.NaN; - - ApplyCustomText(settings, buttonWidth * rowCount); - } - - // 自定义文字是按钮上方的一行横幅:换行折叠成空格,超长按字符省略;字号随控件尺寸缩放, - // 宽度以按钮面板为上限,避免长文本把悬浮窗撑开。收纳态下 ExpandedContent 隐藏,文字随之隐藏。 - private void ApplyCustomText(FloatingWindowSettingsConfig settings, double contentWidth) - { - var text = (settings.FloatingWindowText ?? string.Empty) - .Replace("\r\n", " ") - .Replace('\r', ' ') - .Replace('\n', ' ') - .Trim(); - var show = settings.EnableFloatingWindowText && text.Length > 0; - CustomTextBlock.IsVisible = show; - if (!show) - { - CustomTextBlock.Text = string.Empty; - return; - } - - CustomTextBlock.Text = text; - // 0 = 跟随悬浮窗尺寸自动缩放(旧行为);显式配置时按像素取值,仍夹在可读区间内 - var configuredFontSize = settings.FloatingWindowTextFontSize; - CustomTextBlock.FontSize = configuredFontSize > 0 - ? Math.Clamp(configuredFontSize, 8, 72) - : Math.Clamp(settings.FloatingWindowSize * 0.25, 11, 20); - CustomTextBlock.MaxWidth = Math.Clamp(contentWidth > 1 ? contentWidth : 160, 120, 360); } private static double GetButtonWidth(int size, string label, int displayStyle, Thickness padding) @@ -704,9 +823,14 @@ private void OnClosing(object? sender, WindowClosingEventArgs e) { if (CanClose || e.CloseReason is WindowCloseReason.ApplicationShutdown or WindowCloseReason.OSShutdown) { + // 先于 IsVisible 的变更记下"这是关闭而不是收起",否则 OnWindowPropertyChanged 会去藏另一侧。 + _isClosing = true; ViewModel.Config.FloatingWindowSettings.PropertyChanged -= FloatingWindowSettings_OnPropertyChanged; ViewModel.Config.LinkageSettings.PropertyChanged -= LinkageSettings_OnPropertyChanged; _linkageService.StateChanged -= LinkageServiceOnStateChanged; + + // 快选中途关窗(托盘退出/重启)也要把让位的那一侧交还,否则它会一直藏到下次启动。 + App.NotifyQuickPickFinished(this); return; } @@ -716,13 +840,24 @@ private void OnClosing(object? sender, WindowClosingEventArgs e) private void OnLoaded(object? sender, RoutedEventArgs e) { ApplyWindowSettings(EffectiveFloatingWindowSettings); - Dispatcher.UIThread.Post(RestoreStartupPositionAndScheduleDock, DispatcherPriority.Render); + if (!_startupPositionRestored) + { + // 先不透明地等首帧:此刻 Bounds 还是 0/设计尺寸,拿它去量展开宽高、算贴边距离都会 + // 得到错的结论(右侧贴边尤其明显)。真正的判断在首帧布局完成后由 + // RestoreStartupPositionAndScheduleDock 按真实尺寸做,判断结果不是球时再把窗口亮回来。 + _startupDockPending = ShouldRestoreDockedAtStartup(); + if (_startupDockPending) + Opacity = 0; + Dispatcher.UIThread.Post(RestoreStartupPositionAndScheduleDock, DispatcherPriority.Render); + } + // 触发布局更新 Width = 20; } private void OnOpened(object? sender, EventArgs e) { + _hasBeenShown = true; this.ApplyPlatformFeatures(WindowFeatures.SkipTaskSwitcher, enabled: true); ApplyFocusFreeMode(); @@ -734,8 +869,30 @@ private void OnOpened(object? sender, EventArgs e) private async void RestoreStartupPositionAndScheduleDock() { + if (_startupPositionRestored) + return; + + _startupPositionRestored = true; + var width = Math.Max(1, (int)Math.Ceiling(Bounds.Width * RenderScaling)); var height = Math.Max(1, (int)Math.Ceiling(Bounds.Height * RenderScaling)); + + // 上次退出时浮窗已经是收纳球(保存位置贴着屏幕边缘、且开启了自动收纳):这次直接以球出现, + // 不再先摊开展开态、等 StickToEdgeRecoverSeconds 秒后才收回去。 + if (_startupDockPending) + { + _startupDockPending = false; + if (TryResolveStartupDock(width, height, out var dockedOnLeft)) + { + _isDockedOnLeft = dockedOnLeft; + await RestoreStartupDockedWindowAsync(); + return; + } + + // 保存位置并不贴边:窗口本来就不该收成球,把首帧前藏起来的展开态亮回来。 + Opacity = 1; + } + if (_edgePinned) { RestorePinnedStartupPosition(width, height); @@ -759,17 +916,129 @@ private async void RestoreStartupPositionAndScheduleDock() Position.Y + height / 2, workingArea.Value.Y + height / 2, Math.Max(workingArea.Value.Y + height / 2, workingArea.Value.Bottom - height / 2)); - Opacity = 0; + await ShowStartupDockedWindowAsync(); + } + + /// + /// 这次启动是否可能要以收纳球出现:只有开启"贴边自动收纳"且恢复秒数不为 0 时, + /// 贴边的保存位置才代表上次是收纳态。秒数为 0 是"拖到边缘也一直展开",绝不能强制收成球。 + /// + private bool ShouldRestoreDockedAtStartup() + { + var settings = EffectiveFloatingWindowSettings; + return settings.StickToEdge && Math.Clamp(settings.StickToEdgeRecoverSeconds, 0, 60) > 0; + } + + /// + /// 首帧布局完成后判断保存位置是不是贴边的收纳态,并把停靠所需的状态一次准备好。 + /// + /// + /// 必须等布局完成再调用:这里要拿窗口真实的展开宽高去算距左右边缘的距离,也要把它记成 + /// 展开尺寸,供之后"从球展开"和 还原展开边界。 + /// + private bool TryResolveStartupDock(int width, int height, out bool dockedOnLeft) + { + dockedOnLeft = false; + if (!ShouldRestoreDockedAtStartup()) + return false; + + var workingArea = GetScreenForWindow(Position, width, height)?.WorkingArea; + if (workingArea is not { } area) + return false; + + if (_edgePinned) + { + // 钉边窗口永远贴在自己那一侧;启动坐标可能还是开启"两侧同时显示"之前的旧位置。 + dockedOnLeft = _pinnedOnLeft; + } + else if (!TryResolveEdgeDock(area, width, out dockedOnLeft)) + { + return false; + } + + CaptureExpandedWindowSize(); + _dockWorkingArea = area; + _dockAnchorCenterY = Math.Clamp( + _dockAnchorCenterY, + area.Y + _expandedWindowHeight / 2, + Math.Max(area.Y + _expandedWindowHeight / 2, area.Bottom - _expandedWindowHeight / 2)); + return true; + } + + /// + /// 上次退出时是收纳态:按保存的边缘与纵向锚点直接落成球,不再先展开再等它收回去。 + /// + private async Task RestoreStartupDockedWindowAsync() + { + var settings = EffectiveFloatingWindowSettings; + + if (_edgePinned) + _isDockedOnLeft = _pinnedOnLeft; + + // 两侧高度统一时纵向锚点是两扇窗共用的:主窗也读副窗锚点,否则只拖动过副窗时 + // 下次启动两侧又会错开。统一锚点对收纳态同样有效(保存的就是窗口中心的 Y)。 + var unifiedAnchor = settings.ShowOnBothSides && settings.SyncBothSidesAnchor; + if ((_isSecondary || unifiedAnchor) && settings.SecondaryAnchorCenterY is { } savedAnchor) + _dockAnchorCenterY = savedAnchor; + + var expandedHeight = _expandedWindowHeight > 0 + ? _expandedWindowHeight + : Math.Max(1, (int)Math.Ceiling(Bounds.Height * RenderScaling)); + var workingArea = _dockWorkingArea + ?? GetScreenForWindow(Position)?.WorkingArea; + if (workingArea is { } area) + { + _dockWorkingArea = area; + _dockAnchorCenterY = Math.Clamp( + _dockAnchorCenterY, + area.Y + expandedHeight / 2, + Math.Max(area.Y + expandedHeight / 2, area.Bottom - expandedHeight / 2)); + } + + await ShowStartupDockedWindowAsync(); + } + + /// + /// 把窗口直接以收纳球的状态呈现:不播收起动画,先把整个窗口透明,等 SizeToContent + /// 量完球的大小、贴到边缘后再显示,因此屏幕上不会闪过一帧展开态。 + /// + private async Task ShowStartupDockedWindowAsync() + { _isDocked = true; + Opacity = 0; ExpandedContent.IsVisible = false; DockButton.Opacity = 1; UpdateDockButton(); - await Dispatcher.UIThread.InvokeAsync(() => { }, DispatcherPriority.Render).GetTask(); - RepositionDockedWindow(); - Opacity = 1; + + try + { + // SizeToContent 要等一帧才会把窗口量成球的大小,这时算贴边位置才不会用成展开尺寸。 + await Dispatcher.UIThread.InvokeAsync(() => { }, DispatcherPriority.Render).GetTask(); + if (_isClosed) + return; + + RepositionDockedWindow(); + } + finally + { + // 定位过程里任何提前返回都不能把窗口留在透明状态:启动时为了让展开态不闪一帧才先置 + // Opacity = 0,漏掉还原就等于浮窗启动后彻底看不见。 + if (!_isClosed) + Opacity = 1; + } + SavePosition(); } + /// 保存的位置是否贴着屏幕左/右边缘;贴着就同时给出它属于哪一侧。 + private bool TryResolveEdgeDock(PixelRect workingArea, int width, out bool onLeft) + { + var distanceToLeft = Math.Abs(Position.X - workingArea.X); + var distanceToRight = Math.Abs(workingArea.Right - (Position.X + width)); + onLeft = distanceToLeft <= distanceToRight; + return Math.Min(distanceToLeft, distanceToRight) <= EdgeSnapDistance; + } + /// /// 钉边窗口的启动定位:横向直接贴到角色对应的边缘,纵向用记住的锚点。 /// @@ -810,6 +1079,10 @@ private void PinExpandedWindowToEdge() if (!_edgePinned || _isDocked || _isDockTransitioning) return; + // 快选面板不是"展开态",钉边的横向计算会把整块面板从指针下横着推开。 + if (IsQuickPickActive) + return; + var width = Math.Max(1, (int)Math.Ceiling(Bounds.Width * RenderScaling)); var height = Math.Max(1, (int)Math.Ceiling(Bounds.Height * RenderScaling)); var workingArea = _dockWorkingArea ?? GetScreenForWindow(Position, width, height)?.WorkingArea; @@ -832,8 +1105,33 @@ private void OnPointerPressed(object? sender, PointerPressedEventArgs e) // 又不丢置顶效果。 ReassertNativeTopmost(); + // 两侧同时显示时,按哪一侧就把另一侧收成球:两扇窗一起展开会互相抢注意力。 + App.NotifyFloatingWindowInteraction(this); + + // 每一次按下都从"这次按下还没有被快选取消"开始:上一次长按被拖窗取消时留下的抑制标记 + // 只对那一次松手有效,不能带到下一次按键上,否则这次按下别的按钮时松手会被吞掉、按钮点不动。 + _quickPickTapSuppressed = false; + + // 快选面板已经开着时又按了一下:那是"确认"而不是拖窗,按当前高亮人数收尾。 + if (TryHandleQuickPickPointerPressed(e)) + { + e.Handled = true; + return; + } + + var isPrimaryContact = IsPrimaryContact(e); + + // 鼠标右键同样算一次长按:Windows 把触控"长按"转成的就是这次右键按下 + //(详见 TryBeginQuickDrawLongPress 的说明)。只认主指针的话,触控长按会整个失效。 + var isSecondaryContact = e.Pointer.Type == PointerType.Mouse + && e.GetCurrentPoint(this).Properties.IsRightButtonPressed; + + // 闪抽按钮支持长按快选:这里只开始计时并画环,刻意不接管指针,短按仍走按钮自己的 Click。 + if ((isPrimaryContact || isSecondaryContact) && TryBeginQuickDrawLongPress(e, e.Source as Visual)) + return; + if (EffectiveFloatingWindowSettings.Draggable - && e.GetCurrentPoint(this).Properties.IsLeftButtonPressed) + && isPrimaryContact) { var source = e.Source as Control; @@ -851,14 +1149,45 @@ private void OnPointerPressed(object? sender, PointerPressedEventArgs e) ++_snapAnimationRevision; _isPendingWindowDrag = true; _isMovingWindow = false; + // 记住这次按下是鼠标还是手指:手指的抖动比鼠标大得多,拖动阈值与"丢松手"兜底 + // 都只对真正是鼠标的那次按下生效,避免触控拖动被抬起键的兜底逻辑提前收尾。 + _windowDragStartedByMouse = e.Pointer.Type == PointerType.Mouse; _windowDragStartScreenPoint = Position + ToPixelPoint(e.GetPosition(this)); _windowDragStartPosition = Position; _windowDragScreen = GetScreenForWindow(Position); } } + /// + /// 这次按下是不是"主指针":鼠标左键,或触控/手写笔的按下。 + /// + /// + /// 触控按下没有鼠标按键状态可读,只按 IsLeftButtonPressed 判断会让手指按在浮窗上 + /// 完全没有反应(拖不动、点不动收纳球、长按也起不来)。指针类型优先,与仓库里 + /// AcceleratingRepeatButton 的判定保持一致。 + /// + private bool IsPrimaryContact(PointerPressedEventArgs e) + { + return e.Pointer.Type is PointerType.Touch or PointerType.Pen + || e.GetCurrentPoint(this).Properties.IsLeftButtonPressed; + } + private void OnPointerMoved(object? sender, PointerEventArgs e) { + // 快选面板打开后这次指针已经被它接管,绝不能再当成拖窗。 + if (TryHandleQuickPickPointerMoved(e)) + return; + + // 松手事件被别的路径吞掉时(快选取消、触控被系统收走),拖动状态会一直挂着, + // 鼠标之后只是悬停也会继续拖着窗口走。这次拖动确实由鼠标开始时,键已抬起就把它收尾。 + if (_isPendingWindowDrag + && _windowDragStartedByMouse + && !e.GetCurrentPoint(this).Properties.IsLeftButtonPressed) + { + CompleteWindowDrag(e.Pointer); + return; + } + if (_isMovingDockHandle) { MoveDockHandle(e); @@ -871,7 +1200,9 @@ private void OnPointerMoved(object? sender, PointerEventArgs e) var pointerPosition = Position + ToPixelPoint(e.GetPosition(this)); var deltaX = pointerPosition.X - _windowDragStartScreenPoint.X; var deltaY = pointerPosition.Y - _windowDragStartScreenPoint.Y; - if (!_isMovingWindow && Math.Abs(deltaX) < 4 && Math.Abs(deltaY) < 4) + // 手指按下时的自然抖动比鼠标大:阈值太小会把"点一下"当成拖窗,按钮的 Click 就被吞掉了。 + var dragStartDistance = _windowDragStartedByMouse ? MouseDragStartDistance : TouchDragStartDistance; + if (!_isMovingWindow && Math.Abs(deltaX) < dragStartDistance && Math.Abs(deltaY) < dragStartDistance) return; if (!_isMovingWindow) @@ -940,6 +1271,12 @@ private void OnPointerReleased(object? sender, PointerReleasedEventArgs e) { base.OnPointerReleased(e); + if (TryHandleQuickPickPointerReleased(e)) + { + e.Handled = true; + return; + } + if (_isMovingDockHandle) { _isMovingDockHandle = false; @@ -956,13 +1293,37 @@ private void OnPointerReleased(object? sender, PointerReleasedEventArgs e) if (!_isPendingWindowDrag) return; + // 还没真正拖动就松手 = 这是一次普通点击:不置 Handled,按钮自己的 Click 才会照常触发。 + // 拖动状态不能在这里提前清掉:CompleteWindowDrag 靠 _isMovingWindow 判断这次拖动是否 + // 真的发生过,先清掉会让它直接返回,贴边吸附与自动收纳都不会再排上。 + var wasMoving = _isMovingWindow; _isPendingWindowDrag = false; - if (!_isMovingWindow) + if (!wasMoving) return; - _isMovingWindow = false; - e.Pointer.Capture(null); e.Handled = true; + CompleteWindowDrag(e.Pointer); + } + + /// + /// 收尾一次"按下后可能已经拖起来了"的窗口拖动:清掉进行中的拖动状态、交还指针捕获, + /// 再按钉边/贴边设置落位。 + /// + /// + /// 松手被别的逻辑接管(长按快选改判成拖窗后取消)、或拖动中丢了按下状态时也必须走这里。 + /// 以前那些路径只吞掉松手事件、不清理 _isPendingWindowDrag/_isMovingWindow, + /// 结果松手后窗口还挂在拖动状态里,鼠标只是划过去它就一直跟着指针走。 + /// + private void CompleteWindowDrag(IPointer pointer) + { + _isPendingWindowDrag = false; + var wasMoving = _isMovingWindow; + _isMovingWindow = false; + pointer.Capture(null); + + if (!wasMoving) + return; + if (_edgePinned) { Position = GetPinnedWindowPosition(Position.Y); @@ -992,10 +1353,9 @@ private async Task SnapToNearestEdgeAsync() return; } - const int snapDistance = 36; var distanceToLeft = Math.Abs(Position.X - workingArea.Value.X); var distanceToRight = Math.Abs(workingArea.Value.Right - (Position.X + width)); - if (Math.Min(distanceToLeft, distanceToRight) > snapDistance) + if (Math.Min(distanceToLeft, distanceToRight) > EdgeSnapDistance) { SavePosition(); return; @@ -1010,6 +1370,15 @@ private async Task SnapToNearestEdgeAsync() Position.Y, workingArea.Value.Y, Math.Max(workingArea.Value.Y, workingArea.Value.Bottom - height)); + // 低配模式不播吸附动画:直接落到贴边位置,再像动画结束时那样保存并排收纳。 + if (UiMotion.IsReduced) + { + Position = new PixelPoint(targetX, targetY); + SavePosition(); + ScheduleDock(); + return; + } + var start = Position; var animationRevision = ++_snapAnimationRevision; @@ -1076,6 +1445,7 @@ private void ScheduleDock() { if (dockRevision == _dockRevision && !_isDocked + && _quickPickState == QuickPickState.Idle && EffectiveFloatingWindowSettings.StickToEdge) _ = CollapseToDockAsync(); }, TimeSpan.FromSeconds(seconds)); @@ -1092,10 +1462,9 @@ private void ScheduleDockIfAtEdge() if (workingArea is null) return; - const int snapDistance = 36; var distanceToLeft = Math.Abs(Position.X - workingArea.Value.X); var distanceToRight = Math.Abs(workingArea.Value.Right - (Position.X + width)); - if (Math.Min(distanceToLeft, distanceToRight) > snapDistance) + if (Math.Min(distanceToLeft, distanceToRight) > EdgeSnapDistance) return; _isDockedOnLeft = distanceToLeft <= distanceToRight; @@ -1105,7 +1474,10 @@ private void ScheduleDockIfAtEdge() private async Task CollapseToDockAsync() { - if (_isDocked || _isDockTransitioning || !EffectiveFloatingWindowSettings.StickToEdge) + if (_isDocked + || _isDockTransitioning + || _quickPickState != QuickPickState.Idle + || !EffectiveFloatingWindowSettings.StickToEdge) return; _isDockTransitioning = true; @@ -1154,26 +1526,36 @@ await AnimateControlAsync( private void UpdateDockButton() { - var style = EffectiveFloatingWindowSettings.StickToEdgeDisplayStyle; - var size = Math.Clamp(EffectiveFloatingWindowSettings.DockedWindowSize, 28, 96); - var glyph = _isDockedOnLeft ? ">" : "<"; - DockButton.Content = style switch + var settings = EffectiveFloatingWindowSettings; + var size = Math.Clamp(settings.DockedWindowSize, 28, 96); + var text = FloatingWindowDockHandle.ResolveText(settings.StickToEdgeDisplayText, + Langs.Common.Resources.C_PickButtonText); + var textFontSize = Math.Max(12, size * FloatingWindowDockHandle.GetTextFontScale(text.Length)); + + DockButton.Content = settings.StickToEdgeDisplayStyle switch { - 0 => new FluentIcon(FluentIcons.PeopleFilled, size * 0.62), - 1 => new TextBlock + // 图标样式:没配字形/图片时回退到原来的头像图标,配了自定义图片就画图片 + FloatingWindowDockHandle.IconStyle => CreateIconVisual( + string.IsNullOrWhiteSpace(settings.StickToEdgeDisplayIconGlyph) + ? FloatingWindowDockHandle.DefaultIconGlyph + : settings.StickToEdgeDisplayIconGlyph, + IAppHost.TryGetService() + ?.TryLoadBitmap(settings.StickToEdgeDisplayIconImage), + size * 0.62), + // 文字样式:用户自定义(中文一个字、其它语言最多四个),未填写沿用本地化默认文字 + FloatingWindowDockHandle.TextStyle => new TextBlock { - Text = Langs.Common.Resources.C_PickButtonText, - FontSize = Math.Max(12, size * 0.42), + Text = text, + FontSize = textFontSize, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center }, - _ => new TextBlock - { - Text = glyph, - FontSize = Math.Max(14, size * 0.52), - HorizontalAlignment = HorizontalAlignment.Center, - VerticalAlignment = VerticalAlignment.Center - } + // 箭头样式:用方向图标,不再用 “>” / “<” 字符凑出来 + _ => new FluentIcon( + _isDockedOnLeft + ? FloatingWindowDockHandle.LeftArrowGlyph + : FloatingWindowDockHandle.RightArrowGlyph, + size * 0.62) }; DockButton.Width = size; DockButton.Height = size; @@ -1438,6 +1820,14 @@ private static async Task AnimateControlAsync( RelativePoint transformOrigin, int transitionRevision) { + // 低配/关闭动效时直接落终值:连一帧的等待都不占,也不会留下半截动画。 + if (UiMotion.IsReduced) + { + control.RenderTransform = null; + control.Opacity = toOpacity; + return; + } + control.RenderTransformOrigin = transformOrigin; var scaleTransform = new ScaleTransform(fromScale, fromScale); control.RenderTransform = scaleTransform; @@ -1470,8 +1860,8 @@ private void SavePosition() var unifiedAnchor = settings.ShowOnBothSides && settings.SyncBothSidesAnchor; var anchorCenterY = AnchorCenterY; - // 副窗只记住自己的纵向锚点:横向位置由"副窗在右"这个角色决定,写共享的 FloatPosition - // 会让两扇窗在下次启动时抢同一个坐标。 + // 副窗只记住自己的纵向锚点:横向位置由"主窗在哪侧、副窗就在另一侧"这个角色决定, + // 写共享的 FloatPosition 会让两扇窗在下次启动时抢同一个坐标。 if (_isSecondary) { settings.SecondaryAnchorCenterY = anchorCenterY; diff --git a/SecRandom/Views/Fullscreen/FullscreenTextAnimation.cs b/SecRandom/Views/Fullscreen/FullscreenTextAnimation.cs index cdb9be9f4..b80762955 100644 --- a/SecRandom/Views/Fullscreen/FullscreenTextAnimation.cs +++ b/SecRandom/Views/Fullscreen/FullscreenTextAnimation.cs @@ -6,6 +6,7 @@ using System.Text; using System.Threading; using System.Threading.Tasks; +using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Layout; @@ -42,8 +43,20 @@ namespace SecRandom.Views.Fullscreen; /// internal static class FullscreenTextAnimation { - /// 逐字循环的帧间隔:只决定"检查进度"的频率,不决定吐字速度。 - private const int FrameMilliseconds = 16; + /// 逐字循环的最短等待:字已经到期时立刻回到循环顶部补字。 + private const int MinCharacterDelayMilliseconds = 1; + + /// + /// 逐字循环的最长等待:防止设置被写坏后一次睡太久,取消/关窗的响应也更及时。 + /// 每次唤醒只处理"已经到期"的字,所以等待变短不会多吐字。 + /// + private const int MaxCharacterDelayMilliseconds = 250; + + /// + /// 结果文字列宽未知(调用方没给出舞台宽度)时的兜底:0 表示不做固定列宽, + /// 文本框按内容自适应,行为与旧实现一致。 + /// + private const double NoColumnWidth = 0; /// 每秒字数下限,防止设置被写坏后间隔变成无穷大。 private const int MinCharactersPerSecond = 1; @@ -120,18 +133,23 @@ public static IReadOnlyList BuildLines( /// 多人结果不再每人一行(用户 m03587):整段文字按可用宽度自动换行,字号自适应之后 /// 30 个人也能在一屏里排开。头像通过 内联在该成员名字左侧。 /// + /// + /// 结果文字的固定列宽(由窗口按舞台宽度算出)。打字机与直接显示必须用同一个宽度, + /// 否则换行结果会和动画结束时不一致;传 0 时退回按内容自适应。 + /// public static void FillStatic( StackPanel host, IReadOnlyList lines, double bodyFontSize, Color bodyColor, Color accentColor, - IReadOnlyList? avatars = null) + IReadOnlyList? avatars = null, + double textColumnWidth = NoColumnWidth) { host.Children.Clear(); var bodyBrush = new SolidColorBrush(bodyColor); var accentBrush = new SolidColorBrush(accentColor); - var block = CreateFlowingBlock(bodyFontSize, bodyBrush); + var block = CreateFlowingBlock(bodyFontSize, bodyBrush, textColumnWidth); for (var index = 0; index < lines.Count; index++) { @@ -168,6 +186,9 @@ public static void FillStatic( /// 每秒吐出的字符数(来自全屏设置)。每秒字数越低吐得越慢,长文案就播得越久, /// 不会为了控制总时长而跳字。 /// + /// + /// 结果文字的固定列宽(由窗口按舞台宽度算出)。传 0 时退回按内容自适应。 + /// public static async Task PlayAsync( StackPanel host, IReadOnlyList lines, @@ -177,28 +198,34 @@ public static async Task PlayAsync( int charactersPerSecond, Action? completedCue, CancellationToken cancellationToken, - IReadOnlyList? avatars = null) + IReadOnlyList? avatars = null, + double textColumnWidth = NoColumnWidth) { host.Children.Clear(); var bodyBrush = new SolidColorBrush(bodyColor); var accentBrush = new SolidColorBrush(accentColor); var cursors = new List(lines.Count * 3); - var block = CreateFlowingBlock(bodyFontSize, bodyBrush); + var block = CreateFlowingBlock(bodyFontSize, bodyBrush, textColumnWidth); for (var index = 0; index < lines.Count; index++) { var line = lines[index]; + var prefixText = line.Prefix ?? string.Empty; + var resultText = BuildResultFrame(line.Result); + var prefixRun = CreateRun(bodyFontSize, FontWeight.Normal, bodyBrush); + prefixRun.Text = prefixText; block.Inlines?.Add(prefixRun); - cursors.Add(TypewriterCursor.ForText(prefixRun, line.Prefix)); + cursors.Add(TypewriterCursor.ForText(prefixRun, prefixText)); // 头像先占位:整段文字连续排布,不能等吐完再插,否则会整段重排。 AddAvatarInline(block, avatars, index); var resultRun = CreateRun(bodyFontSize * ResultFontScale, FontWeight.SemiBold, accentBrush); + resultRun.Text = resultText; block.Inlines?.Add(resultRun); // 结果帧整体一次性出现,所以只占一个"字"的节奏。 - cursors.Add(TypewriterCursor.ForWhole(resultRun, BuildResultFrame(line.Result))); + cursors.Add(TypewriterCursor.ForWhole(resultRun, resultText)); if (index < lines.Count - 1) { @@ -210,14 +237,20 @@ public static async Task PlayAsync( if (!string.IsNullOrEmpty(line.Suffix)) { var suffixRun = CreateRun(bodyFontSize, FontWeight.Normal, bodyBrush); + suffixRun.Text = line.Suffix; block.Inlines?.Add(suffixRun); cursors.Add(TypewriterCursor.ForText(suffixRun, line.Suffix)); } } - host.Children.Add(block); + // 先用"整段文字"把最终高度量出来,再把文字退回空:从第一帧起文本框就是最终尺寸, + // 吐字过程中就不会重新换行、重新居中,也不会因为多出一行把已经显示的字顶上去。 + AddTypingBlock(host, block, cursors); + + var totalUnits = 0; + foreach (var cursor in cursors) + totalUnits += cursor.Steps.Length; - var totalUnits = cursors.Sum(cursor => cursor.Steps.Length); if (totalUnits == 0) { RevealAll(cursors); @@ -249,7 +282,12 @@ public static async Task PlayAsync( if (revealed >= totalUnits) break; - await Task.Delay(FrameMilliseconds, cancellationToken); + // 睡到下一个字真正到期为止,而不是死循环式地每 16ms 空转:每秒字数低的时候 + // 空转不产出画面,却会反复占用 UI 线程的派发时隙,并把吐字节奏压在帧边界上。 + var nextDueMilliseconds = revealed / (double)perSecond * 1000.0; + var waitMilliseconds = nextDueMilliseconds - stopwatch.Elapsed.TotalMilliseconds; + var delayMilliseconds = WaitMilliseconds(waitMilliseconds); + await Task.Delay(delayMilliseconds, cancellationToken); } } catch (OperationCanceledException) @@ -283,9 +321,29 @@ private static void RevealAll(List cursors) cursor.RevealAll(); } - /// 整段连续文字的文本框:按可用宽度自动换行、居中排版(多人结果不再一人一行)。 - private static TextBlock CreateFlowingBlock(double bodyFontSize, IBrush bodyBrush) - => new() + /// 把"还有多久到下一个字"换算成可以交给 的毫秒数。 + private static int WaitMilliseconds(double waitMilliseconds) + { + if (!double.IsFinite(waitMilliseconds) || waitMilliseconds <= 0) + return MinCharacterDelayMilliseconds; + + return (int)Math.Clamp( + Math.Ceiling(waitMilliseconds), + MinCharacterDelayMilliseconds, + MaxCharacterDelayMilliseconds); + } + + /// 整段连续文字的文本框:按固定列宽自动换行、居中排版(多人结果不再一人一行)。 + /// + /// 列宽固定是这套动画的性能前提:文本框尺寸不再随吐字变化,父级不必每帧重新测量/重新居中, + /// 已经显示的换行也不会因为多一个字而重排。 + /// + private static TextBlock CreateFlowingBlock( + double bodyFontSize, + IBrush bodyBrush, + double textColumnWidth = NoColumnWidth) + { + var block = new TextBlock { TextWrapping = TextWrapping.Wrap, TextAlignment = TextAlignment.Center, @@ -294,6 +352,68 @@ private static TextBlock CreateFlowingBlock(double bodyFontSize, IBrush bodyBrus Foreground = bodyBrush }; + if (double.IsFinite(textColumnWidth) && textColumnWidth > 0) + block.Width = textColumnWidth; + + return block; + } + + /// + /// 把打字机文本框放进一个"最终尺寸"的固定画框里,然后清空文字准备逐字显示。 + /// + /// + /// 画框高度用整段文字量出来的最终高度:文字从画框顶部开始生长,框本身既不增高也不居中漂移, + /// 所以已显示的字符在整段动画里一动不动。测量失败(例如字体还没就绪)时退回旧的 + /// 内容自适应高度——画面仍然正确,只是行数变化时会有轻微上移。 + /// + private static void AddTypingBlock(StackPanel host, TextBlock block, List cursors) + { + // 先挂到真实宿主里再量:文本框只有在窗口里才继承到实际字体(MiSans), + // 脱离窗口用 DesiredSize 量出来的行高和渲染时可能对不上,最后一行就会被啃掉或留白。 + host.Children.Add(block); + + var finalHeight = MeasureAttachedHeight(host, block); + if (finalHeight > 0) + { + host.Children.Remove(block); + block.VerticalAlignment = VerticalAlignment.Top; + var frame = new Panel { Height = finalHeight }; + if (double.IsFinite(block.Width) && block.Width > 0) + frame.Width = block.Width; + frame.Children.Add(block); + host.Children.Add(frame); + } + + foreach (var cursor in cursors) + cursor.Reset(); + } + + /// 量出文本框在真实宿主里排版后的高度;列宽未知或量不出来时返回 0。 + /// 测量失败只意味着退回"内容自适应高度",画面仍然正确,只是行数变化时会有轻微上移。 + private static double MeasureAttachedHeight(StackPanel host, TextBlock block) + { + if (!double.IsFinite(block.Width) || block.Width <= 0) + return 0; + + try + { + // 跑一次布局把文本框真正排出来(含继承字体/换行),读它的实际高度。 + host.UpdateLayout(); + var height = block.Bounds.Height; + if (double.IsFinite(height) && height > 0) + return height; + + // 布局还没跑起来(例如预览窗口尚未显示)时退回直接测量。 + block.Measure(new Size(block.Width, double.PositiveInfinity)); + height = block.DesiredSize.Height; + return double.IsFinite(height) && height > 0 ? height : 0; + } + catch + { + return 0; + } + } + /// 每个成员的分隔符:小一号的正文色,只负责把相邻结果拉开。 private static Run CreateSeparatorRun(double bodyFontSize, IBrush bodyBrush) { @@ -381,6 +501,14 @@ public void RevealNext() Position++; } + /// 把文字退回空、进度归零:量完最终高度、开始逐字显示之前调用。 + public void Reset() + { + Position = 0; + if (_run is not null) + _run.Text = string.Empty; + } + public void RevealAll() { if (_run is null || Steps.Length == 0) diff --git a/SecRandom/Views/FullscreenNotificationWindow.axaml.cs b/SecRandom/Views/FullscreenNotificationWindow.axaml.cs index 2f84ef4ea..0f46d1922 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; @@ -62,6 +63,19 @@ public partial class FullscreenNotificationWindow : Window /// 结果画面上最多显示几个头像;再多就只是一排缩略图,不如留给结果文字。 private const int MaxAvatars = 8; + /// + /// 结果文字的固定列宽上限,同时也是内容层(Margin 56,40,56,36)内可用的最大宽度。 + /// 焦点:打字机每吐一个字都让文本框宽度跟着变,居中容器就会每帧重新测量并把已有文字推着走, + /// 所以这里给文字一个**从第一帧到最后一帧都不变**的宽度。 + /// + private const double ResultTextColumnMaxWidth = 1600; + + /// 内容层左右各 56 的内边距,共 112:结果列宽必须扣掉它,否则文字会压到边缘。 + private const double ResultTextColumnHorizontalMargin = 112; + + /// 结果列宽的下限:窗口再窄也不把每一行挤成两三个字。 + private const double ResultTextColumnMinWidth = 240; + /// /// 自定义图片背景上固定盖一层压暗,保证文字可读;其余背景模式不压暗。 /// 遮罩浓度刻意不做成设置项——主题/纯色/渐变本来就是用户选的配色,再压一层只会让它们变脏。 @@ -313,7 +327,8 @@ await FullscreenTextAnimation.PlayAsync( settings.EffectiveTypewriterCharactersPerSecond, cue, cts.Token, - BuildAvatarControls(snapshot)); + BuildAvatarControls(snapshot), + ResolveResultColumnWidth()); break; case FullscreenAnimationStyle.Direct: @@ -1116,7 +1131,8 @@ private void ShowStatic( _bodyFontSize, _bodyColor, _accentColor, - snapshot is null ? null : BuildAvatarControls(snapshot)); + snapshot is null ? null : BuildAvatarControls(snapshot), + ResolveResultColumnWidth()); } /// @@ -1140,11 +1156,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) { @@ -1250,6 +1267,23 @@ private double ComputeBodyFontSize( return (width, height); } + /// + /// 结果文字的固定列宽:舞台宽度扣掉内容层左右内边距,再夹到 [240, 1600]。 + /// + /// + /// 打字机与直接显示共用同一个宽度,换行结果才会和动画结束时完全一致; + /// 同时它让文本框尺寸在整段动画里恒定,父级不再每帧测量/居中(卡顿的主因)。 + /// + private double ResolveResultColumnWidth() + { + var (width, _) = GetStageSize(); + var available = width - ResultTextColumnHorizontalMargin; + if (!double.IsFinite(available) || available <= 0) + return ResultTextColumnMaxWidth; + + return Math.Clamp(available, ResultTextColumnMinWidth, ResultTextColumnMaxWidth); + } + private static bool IsLowSpecMode() { try diff --git a/SecRandom/Views/MainPages/QuickDrawPage.axaml b/SecRandom/Views/MainPages/QuickDrawPage.axaml index b8711d6f6..a67224678 100644 --- a/SecRandom/Views/MainPages/QuickDrawPage.axaml +++ b/SecRandom/Views/MainPages/QuickDrawPage.axaml @@ -5,6 +5,7 @@ xmlns:vm="using:SecRandom.ViewModels.MainPages" xmlns:langs="using:SecRandom.Langs.MainPages.QuickDraw" xmlns:sr="http://secrandom.sectl.cn/schemas/xaml/core" + xmlns:controls="clr-namespace:SecRandom.Core.Controls;assembly=SecRandom.Core" mc:Ignorable="d" d:DesignWidth="460" d:DesignHeight="320" x:Name="QuickDraw" x:Class="SecRandom.Views.MainPages.QuickDrawPage" @@ -27,113 +28,125 @@ VerticalAlignment="Center" FontSize="{Binding InitialFontSize}" FontWeight="SemiBold" - Foreground="{DynamicResource TextFillColorPrimaryBrush}" /> + Foreground="{Binding TextBrush}" /> - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - + + + + + + + + + + + + + + + + - - - - - - - - - - - - - + + + + + \ No newline at end of file diff --git a/SecRandom/Views/MainPages/QuickDrawPage.axaml.cs b/SecRandom/Views/MainPages/QuickDrawPage.axaml.cs index 27bb9a0a5..6a995d2db 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,14 @@ using Avalonia.Controls; using Avalonia.Input; using Avalonia.Interactivity; +using Avalonia.Media; +using Avalonia.Styling; 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 +34,9 @@ public partial class QuickDrawPage : UserControl private int _clickCount; private int _remainingAutoCloseSeconds; + /// 本次自动关闭是否走四周描边;描边创建失败时回退到原有的文字倒计时。 + private bool _usesEdgeCountdown; + public QuickDrawPage() { ViewModel = IAppHost.GetService(); @@ -39,6 +46,7 @@ public QuickDrawPage() ViewModel.PropertyChanged += ViewModel_OnPropertyChanged; ViewModel.Config.EffectiveFloatingWindowSettings.PropertyChanged += FloatingWindowSettings_OnPropertyChanged; UpdateFloatingWindowOpacity(); + ApplyNotificationTheme(ViewModel.NotificationTheme); Unloaded += OnUnloaded; } @@ -79,6 +87,90 @@ 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(); + RootBorder.ClearValue(Border.BackgroundProperty); + RootBorder.ClearValue(Border.BorderBrushProperty); + RootBorder.Margin = new Thickness(6); + CountdownRing.Margin = new Thickness(6); + ClearNotificationTextBrushes(); + ApplyCardInk(null); + return; + } + + // 卡片始终是按采样色着色的实色底,窗口本身不做亚克力:窗口合成材质(DWM acrylic)的 + // tint 由系统明暗主题决定、并不跟着桌面走,会把卡片重新染成白/黑;而前景色是按采样 + // 亮度选的,于是出现"白底白字、黑底黑字"。直接绘制底色才能按同一合成模型计算对比度; + // 整体透明度仍会同时淡化文字与底色。圆角与 6px 外边距因此始终保留,画在透明窗口上。 + RootBorder.Margin = new Thickness(6); + CountdownRing.Margin = new Thickness(6); + + // 卡片底与边框直接写本地值,不再只靠资源键:本地值不经过任何资源查找,也不受样式表、 + // 主题变体或模板里同名键的影响,所以"卡片是什么颜色"和"字是什么颜色"永远是同一份方案。 + RootBorder.Background = new SolidColorBrush(adaptive.Surface); + RootBorder.BorderBrush = new SolidColorBrush(adaptive.Stroke); + + 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) + }; + + // 状态文字与提示文字没有自己的 Foreground 绑定,只靠资源键替换在 Fluent 的样式里不一定生效; + // 这里再给本地值兜一次底,保证"换背景就一定换字色"。 + var foreground = new SolidColorBrush(adaptive.Foreground); + var secondary = new SolidColorBrush(adaptive.SecondaryForeground); + StatusTextBlock.Foreground = foreground; + AutoCloseHintTextBlock.Foreground = secondary; + HistoryGroupHintTextBlock.Foreground = secondary; + HistoryGroupMissingHintTextBlock.Foreground = secondary; + + ApplyCardInk(adaptive); + } + + /// + /// 把"通知卡片现在这层底有多亮"换算成黑/白文字色,并推给结果项。 + /// + /// + /// 非 null 时直接用它的前景色,两者本来就是同一个判据。 + /// 为 null(自适应关闭、低配回退、采样失败)时卡片回到应用主题底色,此时按应用主题的 + /// 明暗取黑/白——绝不能再让结果项沿用强调色当文字色,那正是浅色桌面上"看不清"的来源。 + /// + private void ApplyCardInk(AdaptiveTheme? adaptive) + { + var isDarkTheme = Application.Current?.ActualThemeVariant == ThemeVariant.Dark; + var ink = adaptive?.Foreground + ?? AdaptiveBackdropResolver.FromAppTheme(isDarkTheme).Foreground; + ViewModel.ApplyNotificationInk(new SolidColorBrush(ink)); + } + + private void ClearNotificationTextBrushes() + { + StatusTextBlock.ClearValue(TextBlock.ForegroundProperty); + AutoCloseHintTextBlock.ClearValue(TextBlock.ForegroundProperty); + HistoryGroupHintTextBlock.ClearValue(TextBlock.ForegroundProperty); + HistoryGroupMissingHintTextBlock.ClearValue(TextBlock.ForegroundProperty); + } + private void RootBorder_OnPointerPressed(object? sender, PointerPressedEventArgs e) { if (!App.SupportsProgrammaticWindowPositioning) @@ -136,6 +228,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 +337,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 +381,13 @@ private async Task CloseAfterDelayAsync(int autoCloseRevision) } finally { + // 只有仍然是「当前这次自动关闭」时才收掉描边:更晚的一次已经接管时不能把它的描边藏掉。 if (ReferenceEquals(_autoCloseCts, cts)) + { _autoCloseCts = null; + HideCountdownRing(); + } + cts.Dispose(); } } @@ -276,11 +397,52 @@ 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.ResolvedCountdownStart, + settings.ResolvedCountdownEnd); + 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/MainPages/RemoteDrawPage.axaml b/SecRandom/Views/MainPages/RemoteDrawPage.axaml index 0e2581326..0615954fa 100644 --- a/SecRandom/Views/MainPages/RemoteDrawPage.axaml +++ b/SecRandom/Views/MainPages/RemoteDrawPage.axaml @@ -1,12 +1,9 @@ @@ -31,7 +28,7 @@ @@ -43,13 +40,13 @@ + - @@ -60,7 +57,7 @@ - + @@ -104,174 +101,144 @@ - - - - - - - - - - - - - + - - - + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + \ 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..a5a6e578c 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 @@ -976,6 +342,7 @@ private IEnumerable GetSelectedDataRoots() { yield return "config/settings.json"; yield return "config/device-uuid.json"; + yield return "config/orchestration"; } if (Settings.IncludeList) yield return "list"; if (Settings.IncludeHistory) yield return "history"; @@ -992,7 +359,6 @@ private static string GetBackupDirectory() return Utils.GetDirectoryPath(BackupDirectoryName); } - private static string FormatSize(long bytes) { string[] units = ["B", "KB", "MB", "GB"]; @@ -1014,4 +380,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/BasicSettingsPage.axaml b/SecRandom/Views/SettingsPages/General/BasicSettingsPage.axaml index a365b502c..0cc296c91 100644 --- a/SecRandom/Views/SettingsPages/General/BasicSettingsPage.axaml +++ b/SecRandom/Views/SettingsPages/General/BasicSettingsPage.axaml @@ -106,6 +106,16 @@ + + + + + + - @@ -76,6 +78,106 @@ Glyph="{sr:Fi ShieldCheckmarkFilled}" Margin="0 12 0 4" /> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - + + + + - - + + + +/// +/// The three transfer channels are flat entries of the one source picker, exactly like the export drawer's +/// modes, so choosing "扫码快速导入 / 无网扫码导入 / 会话码导入" takes one click instead of selecting a +/// transfer category and then a second "传输方式" combo box inside it. +/// public partial class TextLibraryImportDrawer : UserControl, INotifyPropertyChanged, IDrawerCloseAware { private const string TableFileTypeName = "TextLibraryTable"; @@ -41,7 +48,6 @@ public partial class TextLibraryImportDrawer : UserControl, INotifyPropertyChang private readonly SettingsTransferQrService _settingsQrService = new(); private TextLibraryImportModeOption _selectedImportModeOption; - private TextLibraryTransferModeOption _selectedTransferModeOption; private IReadOnlyList _pendingTemplates = []; private SettingsTransferQrService.SettingsTransferQrImportAccumulator? _offlineQrImport; private IRosterQrCameraCapture? _qrCameraCapture; @@ -68,17 +74,11 @@ public TextLibraryImportDrawer(TextLibraryService textLibraryService) [ new TextLibraryImportModeOption(TextLibraryImportMode.Table, Text("M_SourceTable")), new TextLibraryImportModeOption(TextLibraryImportMode.Json, Text("M_SourceJson")), - new TextLibraryImportModeOption(TextLibraryImportMode.Transfer, Text("M_SourceTransfer")) - ]; - TransferModes = - [ - new TextLibraryTransferModeOption(TextLibraryTransferMode.QuickQr, Text("M_TransferQuickQr")), - new TextLibraryTransferModeOption(TextLibraryTransferMode.OfflineQr, Text("M_TransferOfflineQr")), - new TextLibraryTransferModeOption(TextLibraryTransferMode.SessionCode, Text("M_TransferSessionCode")) + new TextLibraryImportModeOption(TextLibraryImportMode.QuickQr, Text("M_TransferQuickQr")), + new TextLibraryImportModeOption(TextLibraryImportMode.OfflineQr, Text("M_TransferOfflineQr")), + new TextLibraryImportModeOption(TextLibraryImportMode.SessionCode, Text("M_TransferSessionCode")) ]; _selectedImportModeOption = ImportModes[0]; - _selectedTransferModeOption = TransferModes[0]; - _statusText = Text("M_ImportHint"); DataContext = this; InitializeComponent(); } @@ -93,8 +93,6 @@ event PropertyChangedEventHandler? INotifyPropertyChanged.PropertyChanged public IReadOnlyList ImportModes { get; } - public IReadOnlyList TransferModes { get; } - public TextLibraryImportModeOption SelectedImportModeOption { get => _selectedImportModeOption; @@ -106,22 +104,16 @@ public TextLibraryImportModeOption SelectedImportModeOption _selectedImportModeOption = value; OnPropertyChanged(nameof(SelectedImportModeOption)); NotifyModeChanged(); - _ = StopQrScannerAsync(); - } - } - - public TextLibraryTransferModeOption SelectedTransferModeOption - { - get => _selectedTransferModeOption; - set - { - if (value is null || ReferenceEquals(value, _selectedTransferModeOption) || - value.Value == _selectedTransferModeOption.Value) - return; - _selectedTransferModeOption = value; - OnPropertyChanged(nameof(SelectedTransferModeOption)); - NotifyTransferModeChanged(); - _ = StopQrScannerAsync(); + // Every source produces its own preview, so a leftover preview from the previous source must not + // stay importable after switching (the 导入 button would otherwise import a source that is no longer + // on screen). Transfer modes also own scan/session-code work that has to stop on the way out, and a + // half-received offline QR session must not leak into the next attempt. + ClearPendingTemplates(); + CancelSessionCodeVerification(); + _offlineQrImport = null; + NotifyOfflineQrStats(); + StatusText = string.Empty; + _ = StopQrScannerAsync(keepStatus: true); } } @@ -129,13 +121,17 @@ public TextLibraryTransferModeOption SelectedTransferModeOption public bool IsJsonMode => _selectedImportModeOption.Value == TextLibraryImportMode.Json; - public bool IsTransferMode => _selectedImportModeOption.Value == TextLibraryImportMode.Transfer; + public bool IsQuickQrMode => _selectedImportModeOption.Value == TextLibraryImportMode.QuickQr; + + public bool IsOfflineQrMode => _selectedImportModeOption.Value == TextLibraryImportMode.OfflineQr; - public bool IsQuickQrMode => _selectedTransferModeOption.Value == TextLibraryTransferMode.QuickQr; + public bool IsSessionCodeMode => _selectedImportModeOption.Value == TextLibraryImportMode.SessionCode; - public bool IsOfflineQrMode => _selectedTransferModeOption.Value == TextLibraryTransferMode.OfflineQr; + /// Any of the three device-transfer sources, i.e. the whole QR/session-code panel. + public bool IsQrMode => IsQuickQrMode || IsOfflineQrMode || IsSessionCodeMode; - public bool IsSessionCodeMode => _selectedTransferModeOption.Value == TextLibraryTransferMode.SessionCode; + /// The two camera-based sources; a session code is typed, not scanned. + public bool IsScannerMode => IsQuickQrMode || IsOfflineQrMode; public bool IsCameraPreviewSupported => _qrCameraCaptureFactory.IsPreviewSupported; @@ -195,6 +191,8 @@ public string JsonText public string JsonCountText => string.Format(Text("C_JsonCountFormat"), _jsonText.Length, TextLibraryImporter.MaxJsonImportChars); + public string AiPromptText => TextLibraryPrompt.Build(LR.Culture ?? CultureInfo.CurrentUICulture); + public string JsonStatusText { get => _jsonStatusText; @@ -261,14 +259,11 @@ private void NotifyModeChanged() { OnPropertyChanged(nameof(IsTableMode)); OnPropertyChanged(nameof(IsJsonMode)); - OnPropertyChanged(nameof(IsTransferMode)); - } - - private void NotifyTransferModeChanged() - { OnPropertyChanged(nameof(IsQuickQrMode)); OnPropertyChanged(nameof(IsOfflineQrMode)); OnPropertyChanged(nameof(IsSessionCodeMode)); + OnPropertyChanged(nameof(IsQrMode)); + OnPropertyChanged(nameof(IsScannerMode)); } private void NotifyPreviewChanged() @@ -300,7 +295,7 @@ private void ValidateJson() { if (string.IsNullOrWhiteSpace(_jsonText)) { - JsonStatusText = Text("M_JsonEmpty"); + JsonStatusText = string.Empty; JsonStatusIsError = false; JsonErrorText = string.Empty; ClearPendingTemplates(); @@ -334,6 +329,23 @@ private void ValidateJson() SetPendingTemplates(result.Templates, string.Format(Text("M_PreviewCount"), result.Templates.Count)); } + private async void CopyAiPromptButton_OnClick(object? sender, RoutedEventArgs e) + { + var topLevel = TopLevel.GetTopLevel(this); + if (topLevel?.Clipboard is null) + return; + + try + { + await topLevel.Clipboard.SetTextAsync(AiPromptText); + this.ShowSuccessToast(Text("M_JsonAiCopied")); + } + catch (Exception exception) + { + this.ShowErrorToast(Text("M_OperationFailed"), exception); + } + } + private async void FileImportButton_OnClick(object? sender, RoutedEventArgs e) { var topLevel = TopLevel.GetTopLevel(this); @@ -462,7 +474,7 @@ private void ReleaseTemporaryFile() private async void ScanButton_OnClick(object? sender, RoutedEventArgs e) { - if (_isDrawerClosed || !IsTransferMode) + if (_isDrawerClosed || !IsScannerMode) return; if (IsScanning) { @@ -753,16 +765,9 @@ public enum TextLibraryImportMode { Table, Json, - Transfer -} - -public enum TextLibraryTransferMode -{ QuickQr, OfflineQr, SessionCode } public sealed record TextLibraryImportModeOption(TextLibraryImportMode Value, string Label); - -public sealed record TextLibraryTransferModeOption(TextLibraryTransferMode Value, string Label); diff --git a/SecRandom/Views/SettingsPages/Personalized/FloatingWindowButtonEditorView.axaml.cs b/SecRandom/Views/SettingsPages/Personalized/FloatingWindowButtonEditorView.axaml.cs index 27f6b7606..9c288a915 100644 --- a/SecRandom/Views/SettingsPages/Personalized/FloatingWindowButtonEditorView.axaml.cs +++ b/SecRandom/Views/SettingsPages/Personalized/FloatingWindowButtonEditorView.axaml.cs @@ -135,76 +135,8 @@ private async Task PickBuiltInIconAsync() if (topLevel is null) return; - var search = new TextBox - { - PlaceholderText = FloatingWindowButtonUi.Text("M_IconSearchPlaceholder"), - Width = 430 - }; - - var count = new TextBlock { Classes = { "caption" } }; - var list = new DataGrid - { - Height = 320, - Width = 430, - AutoGenerateColumns = false, - CanUserSortColumns = false, - CanUserReorderColumns = false, - CanUserResizeColumns = true, - GridLinesVisibility = DataGridGridLinesVisibility.Horizontal, - HeadersVisibility = DataGridHeadersVisibility.Column, - IsReadOnly = true, - SelectionMode = DataGridSelectionMode.Single - }; - list.Columns.Add(new DataGridTemplateColumn - { - Header = FloatingWindowButtonUi.Text("C_Icon"), - Width = new DataGridLength(64), - CellTemplate = new FuncDataTemplate((choice, _) => choice is null - ? null - : new SecRandom.Core.Controls.FluentIcon(choice.Glyph, 20) - { - HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Center, - VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center - }) - }); - list.Columns.Add(new DataGridTextColumn - { - Header = FloatingWindowButtonUi.Text("C_Label"), - Width = new DataGridLength(1, DataGridLengthUnitType.Star), - Binding = new Avalonia.Data.Binding(nameof(IconChoice.Name)) - }); - - var panel = new StackPanel - { - Spacing = 8, - Children = { search, count, list } - }; - - var dialog = new FluentAvalonia.UI.Controls.FAContentDialog - { - Title = FloatingWindowButtonUi.Text("M_IconPickerTitle"), - Content = panel, - PrimaryButtonText = FloatingWindowButtonUi.Text("C_UseIcon"), - CloseButtonText = FloatingWindowButtonUi.Text("C_Cancel"), - DefaultButton = FluentAvalonia.UI.Controls.FAContentDialogButton.Primary, - IsPrimaryButtonEnabled = false - }; - - void ApplyFilter() - { - var matches = FloatingWindowButtonUi.FilterIcons(search.Text); - list.ItemsSource = matches; - count.Text = FloatingWindowButtonUi.Format("M_IconCountFormat", matches.Count); - } - - list.SelectionChanged += (_, _) => - dialog.IsPrimaryButtonEnabled = list.SelectedItem is IconChoice; - search.TextChanged += (_, _) => ApplyFilter(); - ApplyFilter(); - - var result = await dialog.ShowAsync(topLevel); - if (result != FluentAvalonia.UI.Controls.FAContentDialogResult.Primary || - list.SelectedItem is not IconChoice choice) + var choice = await FloatingWindowIconPicker.PickBuiltInAsync(topLevel); + if (choice is null) return; _config.IconGlyph = choice.Glyph; diff --git a/SecRandom/Views/SettingsPages/Personalized/FloatingWindowButtonsSettingsPage.axaml b/SecRandom/Views/SettingsPages/Personalized/FloatingWindowButtonsSettingsPage.axaml index 35abb35c7..22edef7c5 100644 --- a/SecRandom/Views/SettingsPages/Personalized/FloatingWindowButtonsSettingsPage.axaml +++ b/SecRandom/Views/SettingsPages/Personalized/FloatingWindowButtonsSettingsPage.axaml @@ -74,14 +74,14 @@ SelectionChanged="RowsGrid_OnSelectionChanged" DoubleTapped="RowsGrid_OnDoubleTapped"> - + - + diff --git a/SecRandom/Views/SettingsPages/Personalized/FloatingWindowButtonsSettingsPage.axaml.cs b/SecRandom/Views/SettingsPages/Personalized/FloatingWindowButtonsSettingsPage.axaml.cs index 1edfaa4ed..5942dc8db 100644 --- a/SecRandom/Views/SettingsPages/Personalized/FloatingWindowButtonsSettingsPage.axaml.cs +++ b/SecRandom/Views/SettingsPages/Personalized/FloatingWindowButtonsSettingsPage.axaml.cs @@ -10,6 +10,7 @@ using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Media.Imaging; +using Avalonia.VisualTree; using FluentAvalonia.UI.Controls; using SecRandom.Core.Abstraction; using SecRandom.Core.Attributes; @@ -27,8 +28,9 @@ namespace SecRandom.Views.SettingsPages.Personalized; /// -/// 管理悬浮窗上的自定义按钮:顶部工具栏 + 只读表格展示, -/// 新增/编辑在右侧抽屉里完成。页面不出现在侧栏(由浮窗管理页的设置卡跳转进来)。 +/// 管理悬浮窗上的自定义按钮:顶部工具栏 + 表格展示, +/// 新增/编辑在右侧抽屉里完成,表格里的启用开关可以直接切换。 +/// 页面不出现在侧栏(由浮窗管理页的设置卡跳转进来)。 /// [PageInfo("settings.personalized.floatingWindowButtons", FluentIcons.AppsListDetailFilled, "settings.personalized", isHide: true)] @@ -87,13 +89,16 @@ event PropertyChangedEventHandler? INotifyPropertyChanged.PropertyChanged private void OnLoaded(object? sender, RoutedEventArgs e) { - _iconService?.Prune(Rows.Select(row => row.Config.IconImage)); + // 收纳手柄的图标图片不属于自定义按钮,但同样存在这个目录里,清理时必须一并保留 + _iconService?.Prune(Rows.Select(row => row.Config.IconImage) + .Append(Settings.StickToEdgeDisplayIconImage)); } private void AddRow(FloatingWindowButtonConfig config) { var preview = _iconService?.TryLoadBitmap(config.IconImage); - Rows.Add(new FloatingWindowButtonRow(config, preview)); + // 启用开关直接写进配置对象,再走 Persist 写盘并通知浮窗刷新 + Rows.Add(new FloatingWindowButtonRow(config, preview, Persist)); } private void NotifyListState() @@ -129,6 +134,10 @@ private void RowsGrid_OnSelectionChanged(object? sender, SelectionChangedEventAr private void RowsGrid_OnDoubleTapped(object? sender, TappedEventArgs e) { + // 启用开关是行内操作,双击开关不应该被当成"编辑这一行"的手势 + if (e.Source is Control source && source.FindAncestorOfType(includeSelf: true) is not null) + return; + if ((e.Source as Control)?.DataContext is FloatingWindowButtonRow row) OpenEditor(row); } @@ -234,7 +243,7 @@ private async void ClearAll_OnClick(object? sender, RoutedEventArgs e) Rows.Clear(); _selectedRow = null; Persist(); - _iconService?.Prune([]); + _iconService?.Prune([Settings.StickToEdgeDisplayIconImage]); this.ShowSuccessToast(Text("M_ClearDone")); } @@ -316,13 +325,17 @@ private void OnPropertyChanged([CallerMemberName] string? propertyName = null) = _propertyChangedHandler?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } -/// 只读表格里的一行:把配置投影成表格列需要的展示值。 -public sealed class FloatingWindowButtonRow +/// 表格里的一行:把配置投影成表格列需要的展示值,启用开关直接写回配置。 +public sealed class FloatingWindowButtonRow : INotifyPropertyChanged { - public FloatingWindowButtonRow(FloatingWindowButtonConfig config, Bitmap? iconPreview) + private readonly Action? _enabledChanged; + + public FloatingWindowButtonRow(FloatingWindowButtonConfig config, Bitmap? iconPreview, + Action? enabledChanged = null) { Config = config; IconPreview = iconPreview; + _enabledChanged = enabledChanged; } public FloatingWindowButtonConfig Config { get; } @@ -331,7 +344,19 @@ public FloatingWindowButtonRow(FloatingWindowButtonConfig config, Bitmap? iconPr public string IconGlyph => Config.IconGlyph; - public bool Enabled => Config.Enabled; + public bool Enabled + { + get => Config.Enabled; + set + { + if (Config.Enabled == value) + return; + + Config.Enabled = value; + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Enabled))); + _enabledChanged?.Invoke(); + } + } public bool HasCustomImage => IconPreview is not null; @@ -342,4 +367,6 @@ public FloatingWindowButtonRow(FloatingWindowButtonConfig config, Bitmap? iconPr public string ActionLabel => FloatingWindowButtonUi.ActionLabel(Config.ActionKind); public string TargetLabel => FloatingWindowButtonUi.TargetLabel(Config.ActionKind, Config.ActionTarget); + + public event PropertyChangedEventHandler? PropertyChanged; } diff --git a/SecRandom/Views/SettingsPages/Personalized/FloatingWindowIconPicker.cs b/SecRandom/Views/SettingsPages/Personalized/FloatingWindowIconPicker.cs new file mode 100644 index 000000000..a23a05c13 --- /dev/null +++ b/SecRandom/Views/SettingsPages/Personalized/FloatingWindowIconPicker.cs @@ -0,0 +1,97 @@ +using System.Threading.Tasks; +using Avalonia.Controls; +using Avalonia.Controls.Templates; +using Avalonia.Data; +using Avalonia.Layout; +using Avalonia.Media; +using FluentAvalonia.UI.Controls; +using SecRandom.Core.Controls; + +namespace SecRandom.Views.SettingsPages.Personalized; + +/// +/// 内置图标选择对话框:自定义按钮和收纳手柄共用同一套搜索、预览和选中逻辑, +/// 这样两处的图标列表(精选优先、搜索上限)不会各写一份。 +/// +internal static class FloatingWindowIconPicker +{ + /// 弹出图标选择器;用户取消或没有选中时返回 null。 + public static async Task PickBuiltInAsync(TopLevel topLevel) + { + var search = new TextBox + { + PlaceholderText = FloatingWindowButtonUi.Text("M_IconSearchPlaceholder"), + Width = 430 + }; + + var count = new TextBlock { Classes = { "caption" } }; + var list = new DataGrid + { + Height = 320, + Width = 430, + AutoGenerateColumns = false, + CanUserSortColumns = false, + CanUserReorderColumns = false, + CanUserResizeColumns = true, + GridLinesVisibility = DataGridGridLinesVisibility.Horizontal, + HeadersVisibility = DataGridHeadersVisibility.Column, + IsReadOnly = true, + SelectionMode = DataGridSelectionMode.Single + }; + list.Columns.Add(new DataGridTemplateColumn + { + Header = new TextBlock + { + Text = FloatingWindowButtonUi.Text("C_Icon"), + TextWrapping = TextWrapping.NoWrap + }, + Width = new DataGridLength(72), + CellTemplate = new FuncDataTemplate((choice, _) => choice is null + ? null + : new FluentIcon(choice.Glyph, 20) + { + HorizontalAlignment = HorizontalAlignment.Center, + VerticalAlignment = VerticalAlignment.Center + }) + }); + list.Columns.Add(new DataGridTextColumn + { + Header = FloatingWindowButtonUi.Text("C_Label"), + Width = new DataGridLength(1, DataGridLengthUnitType.Star), + Binding = new Binding(nameof(IconChoice.Name)) + }); + + var panel = new StackPanel + { + Spacing = 8, + Children = { search, count, list } + }; + + var dialog = new FAContentDialog + { + Title = FloatingWindowButtonUi.Text("M_IconPickerTitle"), + Content = panel, + PrimaryButtonText = FloatingWindowButtonUi.Text("C_UseIcon"), + CloseButtonText = FloatingWindowButtonUi.Text("C_Cancel"), + DefaultButton = FAContentDialogButton.Primary, + IsPrimaryButtonEnabled = false + }; + + void ApplyFilter() + { + var matches = FloatingWindowButtonUi.FilterIcons(search.Text); + list.ItemsSource = matches; + count.Text = FloatingWindowButtonUi.Format("M_IconCountFormat", matches.Count); + } + + list.SelectionChanged += (_, _) => + dialog.IsPrimaryButtonEnabled = list.SelectedItem is IconChoice; + search.TextChanged += (_, _) => ApplyFilter(); + ApplyFilter(); + + var result = await dialog.ShowAsync(topLevel); + return result == FAContentDialogResult.Primary && list.SelectedItem is IconChoice choice + ? choice + : null; + } +} \ No newline at end of file diff --git a/SecRandom/Views/SettingsPages/Personalized/FloatingWindowSettingsPage.axaml b/SecRandom/Views/SettingsPages/Personalized/FloatingWindowSettingsPage.axaml index 28f1196ea..d3d398ec5 100644 --- a/SecRandom/Views/SettingsPages/Personalized/FloatingWindowSettingsPage.axaml +++ b/SecRandom/Views/SettingsPages/Personalized/FloatingWindowSettingsPage.axaml @@ -70,34 +70,6 @@ - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ 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 @@ + + + + + + + + + + + +