Compare commits

...
Author SHA1 Message Date
poli0981andClaude Fable 5.1 d079899d5b feat(app): the library import -- Steam, GOG Galaxy, Epic and itch.io through a review checklist, hooking off for every row (P4 PR-4)
LibraryImporter over four IStoreLibrarySource adapters: Steam
(libraryfolders.vdf + appmanifest_*.acf through a ValveKeyValues
reader), GOG (the HKLM registry keys, read-only, under whichever hive
and key a caller names), Epic (Manifests\*.item), itch (gzipped
receipts). Steam and itch do not name the game's executable:
ExecutableLocator walks three levels, drops helpers by name fragment
and takes the largest -- a guess the review marks as such.

File > Import library... shows the checklist, adds what was ticked
exactly as File > Add game... would -- hooking off, FR-1.2 -- and
writes the store's platform, id and version through the new
IGameRepository.ApplyStoreMetadataAsync under the same provenance rule
as a detection write. Nothing is launched, nothing is fetched.

Tests: ValveKeyValuesTests, StoreLibrarySourcesTests,
LibraryImporterTests, ImportLibraryFlowTests, SqliteGameRepositoryTests.
15 App strings en/vi/ja. Docs: 05_DETECTION, 06_DATA_MODEL, 08_UI,
14_TESTING, HANDOFF, 15_ROADMAP, CHANGELOG.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-14 22:32:41 +07:00
43 changed files with 1886 additions and 13 deletions

No files matched your search

+24
View File
@@ -19,6 +19,30 @@ GitHub release body, so a missing section will mean an empty release note.
### Added
- **P4 PR-4 — the library import: Steam, GOG Galaxy, Epic and itch.io through a review checklist, hooking off for
every row (FR-1.2, 2026-09-14).** `Application.Import.LibraryImporter` over four `IStoreLibrarySource` adapters in
`Infrastructure.Import`: `SteamLibrarySource` (`libraryfolders.vdf` + `appmanifest_*.acf` through a new
`ValveKeyValues` reader, the root from `HKCU\Software\Valve\Steam\SteamPath`), `GogLibrarySource` (the
`HKLM\SOFTWARE\WOW6432Node\GOG.com\Games` keys, read-only, whichever hive and key a caller names so a test uses
its own), `EpicLibrarySource` (`Manifests\*.item`: `DisplayName`, `InstallLocation`, `LaunchExecutable`,
`AppName`, `AppVersionString`), `ItchLibrarySource` (`apps\*\.itch\receipt.json.gz`). Steam and itch do not name
the game's executable: `ExecutableLocator` walks the install three levels deep, drops helpers by name fragment
(crash handlers, installers, redistributables, anti-cheat services, updaters) and takes the largest — a guess the
review marks "guessed — check it". Discovery joins every title to the ledger: the store's executable or the
guess, "already in the library", "no executable found" (a store record that outlived the install). File ▸ Import
library… (`ImportLibraryFlow`) shows the checklist (`ImportReviewPrompt` / `Dialogs/ImportReviewContent`, a
`DataGrid` with a tick column, select all / none, the count), adds what was ticked exactly as File ▸ Add game…
would — **hooking off** — writes the store's platform, id and version through the new
`IGameRepository.ApplyStoreMetadataAsync` under the same provenance rule as a detection write (the user's
value is never overwritten), and shows the Games page. Nothing is launched, nothing is fetched. The first-run
step 4 now points at the menu rather than saying "later build". Tests: `ValveKeyValuesTests`,
`StoreLibrarySourcesTests` (fixtures the tests write: two Steam library folders, GOG under a test HKCU key,
Epic `.item`, an itch receipt gzipped in the test, the locator), `LibraryImporterTests` (the join, the ticked
subset, a store that throws, one executable under two stores), `ImportLibraryFlowTests` (end to end over real
files and a scratch ledger; nothing found; cancel; the review's counting), `SqliteGameRepositoryTests` (the
store write's provenance). 15 App strings en/vi/ja. Docs: `05_DETECTION` §Platform signatures built note (with
the privacy line), `06_DATA_MODEL` §Writer ownership, `08_UI` §Shell menu note + §First-run step 4,
`14_TESTING`, HANDOFF §P4, `15_ROADMAP` §P4.
- **P4 PR-3 — the bug report's steps 3–4, Help ▸ Documentation, and File ▸ Export as the submenu it was specified
as (2026-09-14).** `App/Services/BugReportFlow` is the one flow behind Help ▸ Report a bug… and the Logs page's
button: step 2's zip where the user says, then step 3's `ContentDialog` (`BugReportPreviewPrompt` /
+18
View File
@@ -160,6 +160,24 @@ Everything else in the table is in the data and has a fixture; `rules-validate.p
**Auto-import (FR-1.2):** Steam via `libraryfolders.vdf` → all `appmanifest_*.acf`; GOG via `HKLM\SOFTWARE\WOW6432Node\GOG.com\Games\*`; Epic via `Manifests\*.item`; itch by receipt scan. Import presents a review checklist; nothing is launched, nothing is hooked on import.
> **Built 2026-09-14 (P4 PR-4).** `Application.Import.LibraryImporter` over four `IStoreLibrarySource` adapters in
> `Infrastructure.Import` — `SteamLibrarySource` (`libraryfolders.vdf` + `appmanifest_*.acf` through
> `ValveKeyValues`, the Steam root from `HKCU\Software\Valve\Steam\SteamPath`), `GogLibrarySource` (the HKLM
> keys, read-only, the first HKLM read in the tree), `EpicLibrarySource` (`*.item` JSON: `DisplayName`,
> `InstallLocation`, `LaunchExecutable`, `AppName`, `AppVersionString`), `ItchLibrarySource`
> (`%APPDATA%\itch\apps\*\.itch\receipt.json.gz`). **Two stores do not name the game's executable** (Steam,
> itch): `ExecutableLocator` walks the install three levels deep, drops the helpers by name fragment and takes
> the largest — a *guess the review list marks as such*; GOG's `exe` and Epic's `LaunchExecutable` are the store's
> own. The review (`ImportReviewPrompt`) ticks only what can be imported: a row already in the library or with no
> executable on disk cannot be. Every added row lands exactly as File ▸ Add game… lands it — hooking off — and
> the store's platform, id and version go through `IGameRepository.ApplyStoreMetadataAsync` under the same
> provenance rule as a detection write (a value the user typed is never overwritten). The table above says
> "walk up to the nearest manifest" for the per-game metadata extractors; those are still unbuilt
> (`GameFileProbe` keeps `manifest_field` uncollected) — the import reads the launchers' own indexes instead.
> **Privacy:** local files and registry keys the launchers already wrote, read-only; no process is touched, nothing
> is fetched (CLAUDE.md rule 8's "opt-in store metadata" is the online lookup, which does not exist). First-run
> step 4 now points at File ▸ Import library… rather than saying "later build".
**Publisher/version order:** store manifest → PE `CompanyName`/`ProductVersion` → *(opt-in)* Steam `appdetails` lookup, cached 7 days.
## Capability hints (explicitly labelled as such)
+1 -1
View File
@@ -2,7 +2,7 @@
`%LOCALAPPDATA%\FrameLedger\ledger.db`. Pragmas: `journal_mode=WAL`, `synchronous=NORMAL`, `foreign_keys=ON`, `busy_timeout=5000`. `Microsoft.Data.Sqlite` + Dapper; all writes in explicit transactions.
**Writer ownership:** Agent writes `sessions`, `session_segments`, `frame_blobs`, `sensor_blobs`, `hardware_snapshots`, the hook-state columns on `games`, **and since P4 PR-1 (2026-09-14) the *detected* columns on `games`** — `engine`, `engine_version`, `platform` under the per-field provenance rule (`05_DETECTION` §Caching: a `user` field is never touched), `capability_flags` whole, and the cache key `detection_rules_version` / `detection_exe_size_bytes` / `detection_exe_mtime_ms` — through `IGameRepository.ApplyDetectionAsync` only. The UI and the Agent were both already writers of `games`; this adds columns to the Agent's half, not a third writer (HANDOFF §P4). UI writes `games` (user-editable fields — since P3 PR-3 that is the FR-1.3 metadata, the `*_default` tri-states, and `removed_at`; never a `hook_*` column), `session_annotations` (tags, notes, and since schema 0002 the FR-8.3 overrides — which is WHY they are on this table and not on `sessions`), `settings`, `legal_acceptance`. Both read everything. The ports say the same in their names: `IGameRepository.UpdateMetadataAsync` / `SetTriStateDefaultAsync` / `RemoveAsync`, `ISessionAnnotationRepository`, `RegisteredSettings`, `ILegalAcceptanceStore.RecordAsync` (all P3 PR-3).
**Writer ownership:** Agent writes `sessions`, `session_segments`, `frame_blobs`, `sensor_blobs`, `hardware_snapshots`, the hook-state columns on `games`, **and since P4 PR-1 (2026-09-14) the *detected* columns on `games`** — `engine`, `engine_version`, `platform` under the per-field provenance rule (`05_DETECTION` §Caching: a `user` field is never touched), `capability_flags` whole, and the cache key `detection_rules_version` / `detection_exe_size_bytes` / `detection_exe_mtime_ms` — through `IGameRepository.ApplyDetectionAsync` only. The UI and the Agent were both already writers of `games`; this adds columns to the Agent's half, not a third writer (HANDOFF §P4). **And since P4 PR-4 the UI's library import writes `platform`, `store_id` and `game_version` through `ApplyStoreMetadataAsync`** — the same per-field provenance rule, badged `detected` (a store's record is not the user's typing), on columns the UI already owned. UI writes `games` (user-editable fields — since P3 PR-3 that is the FR-1.3 metadata, the `*_default` tri-states, and `removed_at`; never a `hook_*` column), `session_annotations` (tags, notes, and since schema 0002 the FR-8.3 overrides — which is WHY they are on this table and not on `sessions`), `settings`, `legal_acceptance`. Both read everything. The ports say the same in their names: `IGameRepository.UpdateMetadataAsync` / `SetTriStateDefaultAsync` / `RemoveAsync`, `ISessionAnnotationRepository`, `RegisteredSettings`, `ILegalAcceptanceStore.RecordAsync` (all P3 PR-3).
## Schema (v2 — hook architecture)
+7 -3
View File
@@ -33,8 +33,12 @@ The Menu sits in its own row **below** the TitleBar (never inside the drag regio
> (`Services/SessionSelection`, `SessionExportService` over the summary window's own writers; no selection says
> so in the strip), Chart PNG opens that session's summary window, where the plot is. Help ▸ Documentation opens
> the README (`IssueLink.Documentation`; `docs/` is developer-facing). Help ▸ Report a bug… runs
> `BugReportFlow` (`10_LOGGING` §Bug report flow steps 2–4). Tools ▸ Update detection rules is PR-1's. Still
> "later build": File ▸ Import library, Tools ▸ Database maintenance, Help ▸ Check for updates.
> `BugReportFlow` (`10_LOGGING` §Bug report flow steps 2–4). Tools ▸ Update detection rules is PR-1's. **File ▸
> Import library… is PR-4's** (`ImportLibraryFlow` → the review checklist `ImportReviewPrompt` / `Dialogs/ImportReviewContent`,
> a `DataGrid` with a tick column like Compare's picker — store, game, the executable to add, a note for
> "already in the library" / "no executable found" / "guessed — check it"; Add selected lands every row hooking
> off and shows the Games page; `05_DETECTION` §Platform signatures built note). Still "later build": Tools ▸
> Database maintenance, Help ▸ Check for updates.
>
> **Built 2026-09-13 (P3 PR-2): the shell, and only the shell.** `FluentWindow`, the TitleBar with the
> Agent pill as trailing content, the Menu row (every item that a later slice builds says so in a 4 s
@@ -296,7 +300,7 @@ Agent section: elevation state with a plain explanation of what elevation *optio
> state, version, telemetry source, overlay build, CPU temperature, elevated — N/A until the Agent answers.
> **(3) The explainer:** the consent dialog's own reviewed Tier 1 / Tier 2 paragraphs (`Safety_Consent_Hooked` /
> `_NotHooked`, so the two screens cannot drift), that hooking stays off until enabled per game, and that the
> Disclaimer states the risk. **(4)** the import placeholder (P4). D8 unchanged: the gate is not a consent
> Disclaimer states the risk. **(4)** ~~the import placeholder (P4)~~ **since P4 PR-4 (2026-09-14) a real pointer: the stores' libraries are imported from File ▸ Import library… once inside, every row hooking off** (the step itself stays text — the review dialog needs the shell's dialog host, which the first-run window has not). D8 unchanged: the gate is not a consent
> precondition. Tests: `LegalDocumentsTests`, `FirstRunViewModelTests` (required on empty, one Accept = four
> rows at the documents' versions, a moved version re-shows only that document, decline/close write nothing,
> read-only records nothing, the Agent facts), the two steps rendered in `PagesLoadTests`.
+1 -1
View File
@@ -38,7 +38,7 @@ The anti-cheat guard is the one component where a bug can cost someone an accoun
### Parsers & infrastructure
- Shm reader against a synthetic mapping: version mismatch → refuse; torn records skipped; dropped counter propagated.
- ~~PresentMon CSV (Tier 2): header-map building with shuffled/unknown/missing columns, malformed lines, invariant decimal. Fixtures recorded from real runs.~~ **Removed 2026-08-27 with the tool.** Whatever Tier 2 ends up parsing needs its own row, written against the format it actually reads — and the lesson from the one parser that did get written is worth carrying: its CSV's first column was named `Application` while the value it counted was also `Application`, so resolving by NAME rather than position was load-bearing (`spike-notes` §11).
- Steam ACF (KeyValues), GOG `.info`, Epic `.item`, itch receipt — real-world fixtures.
- Steam ACF (KeyValues), GOG `.info`, Epic `.item`, itch receipt — real-world fixtures. **Since P4 PR-4 (2026-09-14):** the import's readers are driven by fixtures the tests write themselves (`ValveKeyValuesTests`, `StoreLibrarySourcesTests` — Steam's two-file shape across two library folders, GOG under a test HKCU key, Epic `.item` JSON, an itch receipt gzipped in the test), not by committed real-world files; a real-world corpus is still worth adding the day a launcher's format drifts.
- `RuleEvaluator`: fixture directory trees per engine, including the "Unity markers present but UE structure too" ordering case.
- Blob codecs round-trip for every series in `frame_blobs` (NaN forbidden — assert), including the two-pair `render_res` encoding and the three-bit `rt_flags` byte. SQLite migrations apply cleanly from an empty file to the current schema, and re-applying is a no-op. (There is no v1→v2 upgrade to test — `06_DATA_MODEL` §Migrations.)
- IPC pipe: framing, split reads, oversize rejection, unknown fields/types ignored, protocol mismatch.
+1 -1
View File
@@ -317,7 +317,7 @@ Agent: watcher, tier selection, injection orchestration, shm drain, telemetry po
WPF UI shell (`16_WPFUI_SYNTAX`), library, per-game hooking consent flow, Dashboard live card showing *measured* settings, session summary, ScottPlot charts, game detail tabs, Compare with tier guarding, segment ribbon, tri-state chips with override, refusal/degradation/unhook notices as first-class UI. **Plus, moved here from P4 on 2026-09-13 (owner):** the command pipe (`07_IPC` §C — P2's decision D10 put it here), i18n en/vi/ja with `tools/resx-audit` (the consent dialog is the first thing that needs a reviewed `.resx`, so it cannot wait), the Legal Gate (FR-11), Settings (FR-10, the kill switch first), the Logs page, tray + toasts. The owner chose the whole of `08_UI` over a shell-first cut; HANDOFF §P3 carries the slice order and the decisions (D11–D17). *Not started as of 2026-09-13: `FrameLedger.App` is the scaffold, `FrameLedger.Shared` has no IPC type, and no `.resx` exists in the tree.*
## P4 — Detection & product polish (1 week)
~~Static rules engine + `detection-rules.json` (engines, platforms, capabilities, **anticheat blocklist**) + validator + fixtures~~ **landed 2026-09-14 (P4 PR-1: the engine existed since P0; the Agent's `DetectionSweep` is its first caller, `ApplyDetectionAsync` its first writer — HANDOFF §P4)**; store auto-import; ~~capability-vs-measured UI separation~~ **(PR-1: the Supports row reads the sweep's flags)**; ~~i18n en/vi/ja; Legal Gate;~~ Velopack + updater (with the hooked-session deferral); bug bundle incl. overlay logs; ~~tray + toasts; Settings;~~ DB maintenance; accessibility pass; the scheduled task (`--install-task`) and the Velopack install hooks. *(The struck items moved to P3 on 2026-09-13 — see §P3.)*
~~Static rules engine + `detection-rules.json` (engines, platforms, capabilities, **anticheat blocklist**) + validator + fixtures~~ **landed 2026-09-14 (P4 PR-1: the engine existed since P0; the Agent's `DetectionSweep` is its first caller, `ApplyDetectionAsync` its first writer — HANDOFF §P4)**; ~~store auto-import~~ **landed 2026-09-14 (P4 PR-4)**; ~~capability-vs-measured UI separation~~ **(PR-1: the Supports row reads the sweep's flags)**; ~~i18n en/vi/ja; Legal Gate;~~ Velopack + updater (with the hooked-session deferral); bug bundle incl. overlay logs; ~~tray + toasts; Settings;~~ DB maintenance; accessibility pass; the scheduled task (`--install-task`) and the Velopack install hooks. *(The struck items moved to P3 on 2026-09-13 — see §P3.)*
## P5 — Ship (3–4 days)
CI/CD with the native build; CodeQL (C# + C++); Dependabot; CHANGELOG; README with the P0 accuracy comparison — **which is not a percentage, and this line used to send its author looking for one**. The decision is recorded under item 3 and in `spike-notes.md` §8: the baseline can answer **none** of item 4's four runtime questions, so the defensible claim is *"the baseline cannot answer four of these five questions at all"*, not *"N% more accurate"*. Overhead + tier cross-validation measurements; release smoke on clean VMs; `v0.1.0-beta.1`.
+4 -2
View File
@@ -1225,8 +1225,10 @@ consumed by the guard; the engine/platform/capability halves are not)~~ **LANDED
engine, validator and corpus already existed; what was missing was a caller and a writer: `DetectionSweep` +
`DetectionHostedService` under `--serve`, `IGameRepository.ApplyDetectionAsync` under the provenance rule,
schema 0004 for the key's exe half (NOT the consent fingerprint), Tools ▸ Update rules wired, the Supports row
filled — status in `CHANGELOG.md`, the decisions in `05_DETECTION` §Caching's built note; store auto-import (Steam / GOG / Epic /
itch.io — the first-run flow's step 4 and File ▸ Import library both say "later build"), ~~the
filled — status in `CHANGELOG.md`, the decisions in `05_DETECTION` §Caching's built note; ~~store auto-import (Steam / GOG / Epic /
itch.io — the first-run flow's step 4 and File ▸ Import library both say "later build")~~ **LANDED 2026-09-14 (P4 PR-4:
`LibraryImporter` over four `IStoreLibrarySource` adapters, the review checklist, `ApplyStoreMetadataAsync` under
the provenance rule, hooking off for every row — `05_DETECTION` §Platform signatures built note)**, ~~the
capability-vs-measured separation in the UI (the game page's Supports row is empty until this)~~ **(PR-1)**, Velopack +
the updater (`11_UPDATER`; the Settings channel row is stored and unused), ~~the bug-report flow's steps 3–5
(`10_LOGGING`: the preview dialog, the GitHub issue link — step 2's bundle exists)~~ **LANDED 2026-09-14 (P4 PR-3:
+27
View File
@@ -5,10 +5,14 @@ using System.Windows.Threading;
using FrameLedger.App.Pages;
using FrameLedger.App.Services;
using FrameLedger.App.ViewModels;
using FrameLedger.Application.Import;
using FrameLedger.Application.Persistence;
using FrameLedger.Application.Settings;
using FrameLedger.Application.Watch;
using FrameLedger.Infrastructure.Import;
using FrameLedger.Infrastructure.Ipc;
using FrameLedger.Infrastructure.Persistence;
using FrameLedger.Infrastructure.Watch;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Serilog;
@@ -271,6 +275,8 @@ public partial class App : System.Windows.Application
services.AddSingleton<SessionSelection>();
services.AddSingleton<SessionExportService>();
AddImport(services);
// The layer registration and the logon task (P3 PR-8b): read from the machine, written by the Agent's flags.
services.AddSingleton<IMaintenanceState, MaintenanceState>();
services.AddSingleton<IAgentTool, AgentTool>();
@@ -281,6 +287,27 @@ public partial class App : System.Windows.Application
services.AddSingleton<IFirstRunFlow, FirstRunFlow>();
}
/// <summary>FR-1.2's library import (P4 PR-4): the stores, the executable guess, the importer over the games port, the review checklist behind a port.</summary>
private static void AddImport(IServiceCollection services)
{
// FR-1.2's library import (P4 PR-4): the four stores read from their own local files and keys, the executable
// guess for the two that name none, the importer over the games port, the review checklist behind a port.
services.AddSingleton<IStoreLibrarySource>(static _ => new SteamLibrarySource());
services.AddSingleton<IStoreLibrarySource>(static _ => new GogLibrarySource());
services.AddSingleton<IStoreLibrarySource>(static _ => new EpicLibrarySource());
services.AddSingleton<IStoreLibrarySource>(static _ => new ItchLibrarySource());
services.AddSingleton<IExecutableLocator, ExecutableLocator>();
services.AddSingleton<IExecutableIdentitySource, ExecutableIdentitySource>();
services.AddSingleton(static sp => new LibraryImporter(
sp.GetServices<IStoreLibrarySource>(),
sp.GetRequiredService<IGameRepository>(),
sp.GetRequiredService<IExecutableIdentitySource>(),
sp.GetRequiredService<IExecutableLocator>(),
static line => Serilog.Log.Information("{Line}", line)));
services.AddSingleton<IImportReview, ImportReviewPrompt>();
services.AddSingleton<ImportLibraryFlow>();
}
/// <summary><c>10_LOGGING</c> §Serilog configuration: <c>logs/ui-.log</c>, daily, 7 kept, 10 MB, the one template; the level follows <c>log.debug</c> at runtime.</summary>
private static void ConfigureLogging() =>
Log.Logger = new LoggerConfiguration()
@@ -0,0 +1,35 @@
<UserControl x:Class="FrameLedger.App.Dialogs.ImportReviewContent"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml"
xmlns:vm="clr-namespace:FrameLedger.App.ViewModels"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
d:DataContext="{d:DesignInstance Type=vm:ImportReviewViewModel}"
mc:Ignorable="d"
MinWidth="640">
<!--
FR-1.2's review checklist: nothing is added until the user says which; a row that is already in the library
or has no executable cannot be ticked. Import never enables hooking (the intro says so).
-->
<StackPanel>
<ui:TextBlock TextWrapping="Wrap" Text="{x:Static vm:ImportReviewViewModel.Intro}" />
<DataGrid Margin="0,10,0,8" MaxHeight="360" AutoGenerateColumns="False" CanUserAddRows="False" HeadersVisibility="Column"
ItemsSource="{Binding Rows}" SelectionMode="Single" IsReadOnly="False">
<DataGrid.Columns>
<DataGridCheckBoxColumn Binding="{Binding IsSelected, UpdateSourceTrigger=PropertyChanged}" Width="40" />
<DataGridTextColumn Header="{x:Static vm:ImportReviewViewModel.ColumnPlatform}" Binding="{Binding PlatformText}" IsReadOnly="True" Width="Auto" />
<DataGridTextColumn Header="{x:Static vm:ImportReviewViewModel.ColumnName}" Binding="{Binding Name}" IsReadOnly="True" Width="2*" />
<DataGridTextColumn Header="{x:Static vm:ImportReviewViewModel.ColumnExe}" Binding="{Binding ExeText}" IsReadOnly="True" Width="3*" />
<DataGridTextColumn Header="{x:Static vm:ImportReviewViewModel.ColumnNote}" Binding="{Binding Note}" IsReadOnly="True" Width="Auto" />
</DataGrid.Columns>
</DataGrid>
<DockPanel>
<StackPanel DockPanel.Dock="Right" Orientation="Horizontal">
<ui:HyperlinkButton Padding="4,0" Content="{x:Static res:Strings.Import_SelectAll}" Command="{Binding SelectAllCommand}" xmlns:res="clr-namespace:FrameLedger.App" />
<ui:HyperlinkButton Padding="4,0" Content="{x:Static res:Strings.Import_SelectNone}" Command="{Binding SelectNoneCommand}" xmlns:res="clr-namespace:FrameLedger.App" />
</StackPanel>
<ui:TextBlock Appearance="Secondary" VerticalAlignment="Center" Text="{Binding SelectedText}" />
</DockPanel>
</StackPanel>
</UserControl>
@@ -0,0 +1,17 @@
using System.Windows.Controls;
using FrameLedger.App.ViewModels;
namespace FrameLedger.App.Dialogs;
/// <summary>The body of FR-1.2's review <c>ContentDialog</c> (P4 PR-4).</summary>
public partial class ImportReviewContent : UserControl
{
public ImportReviewContent(ImportReviewViewModel viewModel)
{
ViewModel = viewModel ?? throw new ArgumentNullException(nameof(viewModel));
DataContext = viewModel;
InitializeComponent();
}
public ImportReviewViewModel ViewModel { get; }
}
+1 -1
View File
@@ -37,7 +37,7 @@
<Menu Grid.Row="1">
<MenuItem Header="{x:Static res:Strings.Menu_File}">
<MenuItem Header="{x:Static res:Strings.Menu_File_AddGame}" Command="{Binding ViewModel.AddGameCommand}" />
<MenuItem Header="{x:Static res:Strings.Menu_File_ImportLibrary}" Command="{Binding ViewModel.NotYetCommand}" />
<MenuItem Header="{x:Static res:Strings.Menu_File_ImportLibrary}" Command="{Binding ViewModel.ImportLibraryCommand}" />
<MenuItem Header="{x:Static res:Strings.Menu_File_Export}">
<MenuItem Header="{x:Static res:Strings.Menu_File_Export_Csv}" Command="{Binding ViewModel.ExportCsvCommand}" />
<MenuItem Header="{x:Static res:Strings.Menu_File_Export_Json}" Command="{Binding ViewModel.ExportJsonCommand}" />
@@ -0,0 +1,13 @@
using FrameLedger.Application.Import;
namespace FrameLedger.App.Services;
/// <summary>
/// FR-1.2's review checklist as a port (P4 PR-4): every candidate the stores found, the user ticks what to add,
/// and the answer is the ticked subset — or null for cancel. The WPF implementation is a <c>ContentDialog</c>
/// (<see cref="ImportReviewPrompt"/>); the flow is tested without it.
/// </summary>
public interface IImportReview
{
Task<IReadOnlyList<ImportCandidate>?> ReviewAsync(IReadOnlyList<ImportCandidate> candidates, CancellationToken ct = default);
}
@@ -0,0 +1,54 @@
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using FrameLedger.App.Pages;
using FrameLedger.Application.Import;
namespace FrameLedger.App.Services;
/// <summary>
/// File ▸ Import library… (FR-1.2, P4 PR-4): discover every installed store's titles, show the review checklist,
/// add what the user ticked — hooking off for every one, as File ▸ Add game… would — and land on the Games page.
/// Nothing is launched, nothing is fetched, nothing is added without a tick.
/// </summary>
[SuppressMessage("Performance", "CA1863:Use 'CompositeFormat'", Justification = "the format strings are resources that follow the UI culture, which changes at runtime; a cached CompositeFormat would pin the first culture")]
public sealed class ImportLibraryFlow
{
private readonly LibraryImporter _importer;
private readonly IImportReview _review;
private readonly IMessageStrip _strip;
private readonly IPageNavigator _navigator;
public ImportLibraryFlow(LibraryImporter importer, IImportReview review, IMessageStrip strip, IPageNavigator navigator)
{
_importer = importer ?? throw new ArgumentNullException(nameof(importer));
_review = review ?? throw new ArgumentNullException(nameof(review));
_strip = strip ?? throw new ArgumentNullException(nameof(strip));
_navigator = navigator ?? throw new ArgumentNullException(nameof(navigator));
}
/// <summary>The report, or null when nothing was found or the user cancelled.</summary>
public async Task<ImportReport?> RunAsync(CancellationToken ct = default)
{
IReadOnlyList<ImportCandidate> candidates = await _importer.DiscoverAsync(ct).ConfigureAwait(true);
if (candidates.Count == 0)
{
_strip.Info(Strings.Import_Title, Strings.Import_NothingFound);
return null;
}
IReadOnlyList<ImportCandidate>? selected = await _review.ReviewAsync(candidates, ct).ConfigureAwait(true);
if (selected is null || selected.Count == 0)
{
return null;
}
ImportReport report = await _importer.ImportAsync(selected, ct).ConfigureAwait(true);
_strip.Success(Strings.Import_Title, string.Format(CultureInfo.CurrentCulture, Strings.Import_Done_Format, report.Added, report.Skipped));
if (report.Added > 0)
{
_navigator.Navigate<GamesPage>();
}
return report;
}
}
@@ -0,0 +1,35 @@
using System.Windows.Data;
using FrameLedger.App.Dialogs;
using FrameLedger.App.ViewModels;
using FrameLedger.Application.Import;
using Wpf.Ui;
using Wpf.Ui.Controls;
namespace FrameLedger.App.Services;
/// <summary>FR-1.2's review checklist in WPF UI: a <c>ContentDialog</c> whose primary button follows the tick count; Cancel adds nothing.</summary>
public sealed class ImportReviewPrompt : IImportReview
{
private readonly IContentDialogService _dialogs;
public ImportReviewPrompt(IContentDialogService dialogs) => _dialogs = dialogs ?? throw new ArgumentNullException(nameof(dialogs));
public async Task<IReadOnlyList<ImportCandidate>?> ReviewAsync(IReadOnlyList<ImportCandidate> candidates, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(candidates);
var viewModel = new ImportReviewViewModel(candidates);
var dialog = new ContentDialog
{
Title = ImportReviewViewModel.Title,
Content = new ImportReviewContent(viewModel),
PrimaryButtonText = Strings.Import_Add,
CloseButtonText = Strings.Common_Cancel,
DefaultButton = ContentDialogButton.Primary,
DialogMaxWidth = 900,
};
_ = dialog.SetBinding(ContentDialog.IsPrimaryButtonEnabledProperty, new Binding(nameof(ImportReviewViewModel.CanImport)) { Source = viewModel, Mode = BindingMode.OneWay });
ContentDialogResult result = await _dialogs.ShowAsync(dialog, ct).ConfigureAwait(true);
return result == ContentDialogResult.Primary ? viewModel.Selected : null;
}
}
+45
View File
@@ -259,6 +259,21 @@ public static class Strings
nameof(Games_Sort_LastPlayed),
nameof(Games_Sort_Name),
nameof(Games_Sort_Playtime),
nameof(Import_Add),
nameof(Import_Column_Exe),
nameof(Import_Column_Name),
nameof(Import_Column_Note),
nameof(Import_Column_Platform),
nameof(Import_Done_Format),
nameof(Import_Intro),
nameof(Import_Note_Already),
nameof(Import_Note_Guessed),
nameof(Import_Note_NoExe),
nameof(Import_NothingFound),
nameof(Import_SelectAll),
nameof(Import_Selected_Format),
nameof(Import_SelectNone),
nameof(Import_Title),
nameof(Latency_Avg),
nameof(Latency_Axis),
nameof(Latency_Empty),
@@ -962,6 +977,36 @@ public static class Strings
public static string Games_Sort_Playtime => ResourceManager.GetString(nameof(Games_Sort_Playtime), Culture) ?? nameof(Games_Sort_Playtime);
public static string Import_Add => ResourceManager.GetString(nameof(Import_Add), Culture) ?? nameof(Import_Add);
public static string Import_Column_Exe => ResourceManager.GetString(nameof(Import_Column_Exe), Culture) ?? nameof(Import_Column_Exe);
public static string Import_Column_Name => ResourceManager.GetString(nameof(Import_Column_Name), Culture) ?? nameof(Import_Column_Name);
public static string Import_Column_Note => ResourceManager.GetString(nameof(Import_Column_Note), Culture) ?? nameof(Import_Column_Note);
public static string Import_Column_Platform => ResourceManager.GetString(nameof(Import_Column_Platform), Culture) ?? nameof(Import_Column_Platform);
public static string Import_Done_Format => ResourceManager.GetString(nameof(Import_Done_Format), Culture) ?? nameof(Import_Done_Format);
public static string Import_Intro => ResourceManager.GetString(nameof(Import_Intro), Culture) ?? nameof(Import_Intro);
public static string Import_Note_Already => ResourceManager.GetString(nameof(Import_Note_Already), Culture) ?? nameof(Import_Note_Already);
public static string Import_Note_Guessed => ResourceManager.GetString(nameof(Import_Note_Guessed), Culture) ?? nameof(Import_Note_Guessed);
public static string Import_Note_NoExe => ResourceManager.GetString(nameof(Import_Note_NoExe), Culture) ?? nameof(Import_Note_NoExe);
public static string Import_NothingFound => ResourceManager.GetString(nameof(Import_NothingFound), Culture) ?? nameof(Import_NothingFound);
public static string Import_SelectAll => ResourceManager.GetString(nameof(Import_SelectAll), Culture) ?? nameof(Import_SelectAll);
public static string Import_Selected_Format => ResourceManager.GetString(nameof(Import_Selected_Format), Culture) ?? nameof(Import_Selected_Format);
public static string Import_SelectNone => ResourceManager.GetString(nameof(Import_SelectNone), Culture) ?? nameof(Import_SelectNone);
public static string Import_Title => ResourceManager.GetString(nameof(Import_Title), Culture) ?? nameof(Import_Title);
public static string Latency_Avg => ResourceManager.GetString(nameof(Latency_Avg), Culture) ?? nameof(Latency_Avg);
public static string Latency_Axis => ResourceManager.GetString(nameof(Latency_Axis), Culture) ?? nameof(Latency_Axis);
+61 -1
View File
@@ -229,6 +229,66 @@
<value>ライブラリをインポート…</value>
<comment>review</comment>
</data>
<data name="Import_Title" xml:space="preserve">
<value>ライブラリを取り込む</value>
<comment>review</comment>
</data>
<data name="Import_Intro" xml:space="preserve">
<value>ストアがインストール済みと報告しているゲームです。追加するものにチェックを付けてください。手動で追加したゲームと同じく、どれもフック無効で始まります。起動も送信もしません。</value>
<comment>review</comment>
</data>
<data name="Import_Column_Platform" xml:space="preserve">
<value>ストア</value>
<comment>review</comment>
</data>
<data name="Import_Column_Name" xml:space="preserve">
<value>ゲーム</value>
<comment>review</comment>
</data>
<data name="Import_Column_Exe" xml:space="preserve">
<value>追加する実行ファイル</value>
<comment>review</comment>
</data>
<data name="Import_Column_Note" xml:space="preserve">
<value>備考</value>
<comment>review</comment>
</data>
<data name="Import_Note_Already" xml:space="preserve">
<value>ライブラリに登録済み</value>
<comment>review</comment>
</data>
<data name="Import_Note_NoExe" xml:space="preserve">
<value>実行ファイルが見つかりません</value>
<comment>review</comment>
</data>
<data name="Import_Note_Guessed" xml:space="preserve">
<value>推定 — 確認してください</value>
<comment>review</comment>
</data>
<data name="Import_Selected_Format" xml:space="preserve">
<value>{1} 件中 {0} 件を選択</value>
<comment>review</comment>
</data>
<data name="Import_SelectAll" xml:space="preserve">
<value>すべて選択</value>
<comment>review</comment>
</data>
<data name="Import_SelectNone" xml:space="preserve">
<value>選択解除</value>
<comment>review</comment>
</data>
<data name="Import_Add" xml:space="preserve">
<value>選択したものを追加</value>
<comment>review</comment>
</data>
<data name="Import_NothingFound" xml:space="preserve">
<value>このマシンの Steam、GOG Galaxy、Epic、itch.io にインストール済みのゲームは見つかりませんでした。</value>
<comment>review</comment>
</data>
<data name="Import_Done_Format" xml:space="preserve">
<value>{0} 件のゲームをフック無効で追加しました。{1} 件はそのままです。</value>
<comment>review</comment>
</data>
<data name="Menu_Help" xml:space="preserve">
<value>ヘルプ(_H)</value>
<comment>review</comment>
@@ -1862,7 +1922,7 @@
<comment>review</comment>
</data>
<data name="FirstRun_Import_Body" xml:space="preserve">
<value>Steam、GOG、Epic、itch.io のライブラリの取り込みは後のビルドで追加されます。今はゲームページからゲームを 1 つずつ追加してください。各ゲームはフックがオフの状態で始まります。</value>
<value>FrameLedger は Steam、GOG Galaxy、Epic、itch.io のインストール済みゲームを読み取り、チェックリストから追加できます — 入った後、ゲームページの「ファイル ▸ ライブラリを取り込む…」から。取り込んだゲームはどれも、手動で追加したものと同じくフック無効で始まります。</value>
<comment>review</comment>
</data>
<data name="FirstRun_Import_Header" xml:space="preserve">
+46 -1
View File
@@ -177,6 +177,51 @@
<data name="Menu_File_ImportLibrary" xml:space="preserve">
<value>Import library…</value>
</data>
<data name="Import_Title" xml:space="preserve">
<value>Import library</value>
</data>
<data name="Import_Intro" xml:space="preserve">
<value>These are the games your stores say are installed. Tick what to add; every one starts with hooking off, exactly as a game you add by hand. Nothing is launched and nothing is sent.</value>
</data>
<data name="Import_Column_Platform" xml:space="preserve">
<value>Store</value>
</data>
<data name="Import_Column_Name" xml:space="preserve">
<value>Game</value>
</data>
<data name="Import_Column_Exe" xml:space="preserve">
<value>Executable to add</value>
</data>
<data name="Import_Column_Note" xml:space="preserve">
<value>Note</value>
</data>
<data name="Import_Note_Already" xml:space="preserve">
<value>Already in the library</value>
</data>
<data name="Import_Note_NoExe" xml:space="preserve">
<value>No executable found</value>
</data>
<data name="Import_Note_Guessed" xml:space="preserve">
<value>Guessed — check it</value>
</data>
<data name="Import_Selected_Format" xml:space="preserve">
<value>{0} of {1} selected</value>
</data>
<data name="Import_SelectAll" xml:space="preserve">
<value>Select all</value>
</data>
<data name="Import_SelectNone" xml:space="preserve">
<value>Select none</value>
</data>
<data name="Import_Add" xml:space="preserve">
<value>Add selected</value>
</data>
<data name="Import_NothingFound" xml:space="preserve">
<value>No installed games were found in Steam, GOG Galaxy, Epic or itch.io on this machine.</value>
</data>
<data name="Import_Done_Format" xml:space="preserve">
<value>{0} game(s) added with hooking off; {1} left as they were.</value>
</data>
<data name="Menu_Help" xml:space="preserve">
<value>_Help</value>
</data>
@@ -1402,7 +1447,7 @@
<value>Finish</value>
</data>
<data name="FirstRun_Import_Body" xml:space="preserve">
<value>Importing a Steam, GOG, Epic or itch.io library arrives with a later build. For now, add games one at a time from the Games page — each one starts with hooking off.</value>
<value>FrameLedger can read what Steam, GOG Galaxy, Epic and itch.io have installed and add them from a checklist — File ▸ Import library… on the Games page, once you are in. Every imported game starts with hooking off, exactly like one you add by hand.</value>
</data>
<data name="FirstRun_Import_Header" xml:space="preserve">
<value>Your library</value>
+46 -1
View File
@@ -172,6 +172,51 @@
<data name="Menu_File_ImportLibrary" xml:space="preserve">
<value>Nhập thư viện…</value>
</data>
<data name="Import_Title" xml:space="preserve">
<value>Nhập thư viện</value>
</data>
<data name="Import_Intro" xml:space="preserve">
<value>Đây là các game mà các store cho biết đã cài. Tích những gì muốn thêm; mọi game đều bắt đầu với hooking tắt, đúng như game bạn thêm thủ công. Không khởi chạy gì và không gửi gì.</value>
</data>
<data name="Import_Column_Platform" xml:space="preserve">
<value>Store</value>
</data>
<data name="Import_Column_Name" xml:space="preserve">
<value>Game</value>
</data>
<data name="Import_Column_Exe" xml:space="preserve">
<value>Tệp thực thi sẽ thêm</value>
</data>
<data name="Import_Column_Note" xml:space="preserve">
<value>Ghi chú</value>
</data>
<data name="Import_Note_Already" xml:space="preserve">
<value>Đã có trong thư viện</value>
</data>
<data name="Import_Note_NoExe" xml:space="preserve">
<value>Không tìm thấy tệp thực thi</value>
</data>
<data name="Import_Note_Guessed" xml:space="preserve">
<value>Đoán — hãy kiểm tra</value>
</data>
<data name="Import_Selected_Format" xml:space="preserve">
<value>Đã chọn {0}/{1}</value>
</data>
<data name="Import_SelectAll" xml:space="preserve">
<value>Chọn tất cả</value>
</data>
<data name="Import_SelectNone" xml:space="preserve">
<value>Bỏ chọn tất cả</value>
</data>
<data name="Import_Add" xml:space="preserve">
<value>Thêm mục đã chọn</value>
</data>
<data name="Import_NothingFound" xml:space="preserve">
<value>Không tìm thấy game nào đã cài trong Steam, GOG Galaxy, Epic hay itch.io trên máy này.</value>
</data>
<data name="Import_Done_Format" xml:space="preserve">
<value>Đã thêm {0} game với hooking tắt; {1} giữ nguyên.</value>
</data>
<data name="Menu_Help" xml:space="preserve">
<value>Trợ _giúp</value>
</data>
@@ -1397,7 +1442,7 @@
<value>Hoàn tất</value>
</data>
<data name="FirstRun_Import_Body" xml:space="preserve">
<value>Nhập thư viện Steam, GOG, Epic hay itch.io sẽ có ở bản sau. Hiện tại, thêm từng game từ trang Game — mỗi game bắt đầu với hooking tắt.</value>
<value>FrameLedger có thể đọc những gì Steam, GOG Galaxy, Epic và itch.io đã cài và thêm chúng từ một danh sách chọn — File ▸ Nhập thư viện… ở trang Game, khi bạn đã vào trong. Mọi game nhập vào đều bắt đầu với hooking tắt, đúng như game bạn thêm thủ công.</value>
</data>
<data name="FirstRun_Import_Header" xml:space="preserve">
<value>Thư viện của bạn</value>
@@ -0,0 +1,35 @@
using CommunityToolkit.Mvvm.ComponentModel;
using FrameLedger.App.Services;
using FrameLedger.Application.Import;
namespace FrameLedger.App.ViewModels;
/// <summary>One row of FR-1.2's review checklist: ticked by default when it can be imported, with the store, the name, the executable the import would add, and why it cannot when it cannot.</summary>
public sealed partial class ImportCandidateViewModel : ObservableObject
{
[ObservableProperty]
private bool _isSelected;
public ImportCandidateViewModel(ImportCandidate candidate)
{
Candidate = candidate ?? throw new ArgumentNullException(nameof(candidate));
_isSelected = candidate.CanImport;
Note = candidate.AlreadyInLibrary ? Strings.Import_Note_Already
: candidate.ExePath is null || candidate.ExecutableMissing ? Strings.Import_Note_NoExe
: candidate.ExecutableGuessed ? Strings.Import_Note_Guessed
: string.Empty;
}
public ImportCandidate Candidate { get; }
public bool CanImport => Candidate.CanImport;
public string PlatformText => Formats.Platform(Candidate.Game.Platform);
public string Name => Candidate.Game.Name;
public string ExeText => Candidate.ExePath ?? Strings.Common_Dash;
/// <summary>Already in the library, no executable found, or a guessed executable the user should check.</summary>
public string Note { get; }
}
@@ -0,0 +1,80 @@
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using FrameLedger.Application.Import;
namespace FrameLedger.App.ViewModels;
/// <summary>FR-1.2's review checklist: every candidate the stores found, ticked by default where it can be imported; the count follows the ticks.</summary>
[SuppressMessage("Performance", "CA1863:Use 'CompositeFormat'", Justification = "the format strings are resources that follow the UI culture, which changes at runtime; a cached CompositeFormat would pin the first culture")]
public sealed partial class ImportReviewViewModel : ObservableObject
{
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(CanImport))]
[NotifyPropertyChangedFor(nameof(SelectedText))]
private int _selectedCount;
public ImportReviewViewModel(IReadOnlyList<ImportCandidate> candidates)
{
ArgumentNullException.ThrowIfNull(candidates);
foreach (ImportCandidate c in candidates)
{
var row = new ImportCandidateViewModel(c);
row.PropertyChanged += OnRowChanged;
Rows.Add(row);
}
Recount();
}
public ObservableCollection<ImportCandidateViewModel> Rows { get; } = [];
public static string Title => Strings.Import_Title;
public static string Intro => Strings.Import_Intro;
public static string ColumnPlatform => Strings.Import_Column_Platform;
public static string ColumnName => Strings.Import_Column_Name;
public static string ColumnExe => Strings.Import_Column_Exe;
public static string ColumnNote => Strings.Import_Column_Note;
public bool CanImport => SelectedCount > 0;
public string SelectedText => string.Format(CultureInfo.CurrentCulture, Strings.Import_Selected_Format, SelectedCount, Rows.Count);
public IReadOnlyList<ImportCandidate> Selected => [.. Rows.Where(static r => r.IsSelected && r.CanImport).Select(static r => r.Candidate)];
[RelayCommand]
private void SelectAll()
{
foreach (ImportCandidateViewModel r in Rows.Where(static r => r.CanImport))
{
r.IsSelected = true;
}
}
[RelayCommand]
private void SelectNone()
{
foreach (ImportCandidateViewModel r in Rows)
{
r.IsSelected = false;
}
}
private void OnRowChanged(object? sender, PropertyChangedEventArgs e)
{
if (string.Equals(e.PropertyName, nameof(ImportCandidateViewModel.IsSelected), StringComparison.Ordinal))
{
Recount();
}
}
private void Recount() => SelectedCount = Rows.Count(static r => r.IsSelected && r.CanImport);
}
@@ -40,11 +40,13 @@ public sealed partial class MainWindowViewModel : ObservableObject, IDisposable
private readonly SessionSelection _selection;
private readonly SessionExportService _exports;
private readonly ISessionSummaryOpener _summaries;
private readonly ImportLibraryFlow _import;
public MainWindowViewModel(AgentConnection agent, ISnackbarService snackbar, IShellPresence shell, IPageNavigator navigator, AddGameFlow addGame, SafetyNotices notices,
BugReportFlow bugReports, IUrlOpener urls, SessionSelection selection, SessionExportService exports, ISessionSummaryOpener summaries)
BugReportFlow bugReports, IUrlOpener urls, SessionSelection selection, SessionExportService exports, ISessionSummaryOpener summaries, ImportLibraryFlow import)
{
Notices = notices ?? throw new ArgumentNullException(nameof(notices));
_import = import ?? throw new ArgumentNullException(nameof(import));
_bugReports = bugReports ?? throw new ArgumentNullException(nameof(bugReports));
_urls = urls ?? throw new ArgumentNullException(nameof(urls));
_selection = selection ?? throw new ArgumentNullException(nameof(selection));
@@ -156,6 +158,10 @@ public sealed partial class MainWindowViewModel : ObservableObject, IDisposable
}
}
/// <summary>File ▸ Import library… (FR-1.2, P4 PR-4): the stores' installed titles through the review checklist; hooking off for every row added.</summary>
[RelayCommand]
private async Task ImportLibraryAsync() => _ = await _import.RunAsync().ConfigureAwait(true);
/// <summary>Help ▸ Documentation (P4 PR-3): the README is the user-facing entry point; `docs/` is the developers'.</summary>
[RelayCommand]
private void Documentation()
@@ -0,0 +1,12 @@
namespace FrameLedger.Application.Import;
/// <summary>
/// Which executable in an install directory is the game, for the stores that do not say (Steam, itch). A port so the
/// importer is tested without a file system; the adapter is <c>Infrastructure.Import.ExecutableLocator</c>. A guess,
/// shown on the review list for the user to accept or untick — never acted on silently.
/// </summary>
public interface IExecutableLocator
{
/// <summary>The most plausible game executable under <paramref name="installDirectory"/>, or null when none is found.</summary>
string? PickPrimary(string installDirectory);
}
@@ -0,0 +1,15 @@
namespace FrameLedger.Application.Import;
/// <summary>
/// One store's installed library, read from its local files (FR-1.2, <c>05_DETECTION</c> §Platform signatures &amp;
/// metadata: Steam's <c>libraryfolders.vdf</c> + <c>appmanifest_*.acf</c>, GOG's registry keys, Epic's
/// <c>Manifests\*.item</c>, itch's receipts). A store that is not installed answers an empty list, never an error;
/// a file that will not parse costs that one entry.
/// </summary>
public interface IStoreLibrarySource
{
/// <summary><c>steam</c> · <c>gog</c> · <c>epic</c> · <c>itch</c> — <c>games.platform</c>'s vocabulary.</summary>
string Platform { get; }
ValueTask<IReadOnlyList<StoreGame>> ListAsync(CancellationToken ct = default);
}
@@ -0,0 +1,12 @@
namespace FrameLedger.Application.Import;
/// <summary>
/// One row of the review checklist (FR-1.2): the store's record, the executable the import would add — the store's
/// own when it names one, else the locator's guess — whether the ledger already has it, and whether the file is
/// there to be read at all. A candidate with no executable cannot be imported and the list says so.
/// </summary>
public sealed record ImportCandidate(StoreGame Game, string? ExePath, bool AlreadyInLibrary, bool ExecutableGuessed, bool ExecutableMissing = false)
{
/// <summary>An executable is known, it is on disk, and the ledger does not have it yet.</summary>
public bool CanImport => ExePath is not null && !ExecutableMissing && !AlreadyInLibrary;
}
@@ -0,0 +1,4 @@
namespace FrameLedger.Application.Import;
/// <summary>What one import did: rows added (hooking off, every one), and candidates left alone (already there, or no executable).</summary>
public sealed record ImportReport(int Added, int Skipped);
@@ -0,0 +1,111 @@
using FrameLedger.Application.Persistence;
using FrameLedger.Application.Watch;
using FrameLedger.Domain.Consent;
namespace FrameLedger.Application.Import;
/// <summary>
/// FR-1.2 in two halves (P4 PR-4): <see cref="DiscoverAsync"/> reads every installed store's library into a review
/// list — the store's executable where it names one, the locator's guess where it does not, and whether the ledger
/// already holds the row — and <see cref="ImportAsync"/> adds the rows the user ticked. <b>Import never enables
/// hooking for anything</b>: a row lands exactly as File ▸ Add game… lands it, hooking off, and the store's
/// platform, id and version are written under the provenance rule so a later correction by the user sticks.
/// Nothing is launched, nothing is fetched (CLAUDE.md rule 8: store metadata is opt-in and this reads only what
/// the launcher already wrote to disk).
/// </summary>
public sealed class LibraryImporter
{
private readonly IReadOnlyList<IStoreLibrarySource> _sources;
private readonly IGameRepository _games;
private readonly IExecutableIdentitySource _identity;
private readonly IExecutableLocator _locator;
private readonly Action<string> _log;
public LibraryImporter(IEnumerable<IStoreLibrarySource> sources, IGameRepository games, IExecutableIdentitySource identity, IExecutableLocator locator, Action<string> log)
{
ArgumentNullException.ThrowIfNull(sources);
_sources = [.. sources];
_games = games ?? throw new ArgumentNullException(nameof(games));
_identity = identity ?? throw new ArgumentNullException(nameof(identity));
_locator = locator ?? throw new ArgumentNullException(nameof(locator));
_log = log ?? throw new ArgumentNullException(nameof(log));
}
/// <summary>Every store's titles, one candidate per executable (the first store to name a path keeps it), in store then name order.</summary>
public async ValueTask<IReadOnlyList<ImportCandidate>> DiscoverAsync(CancellationToken ct = default)
{
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
List<ImportCandidate> candidates = [];
foreach (IStoreLibrarySource source in _sources)
{
IReadOnlyList<StoreGame> games;
try
{
games = await source.ListAsync(ct).ConfigureAwait(false);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidOperationException)
{
_log($"import: {source.Platform} library unreadable — {ex.Message}");
continue;
}
foreach (StoreGame game in games.OrderBy(static g => g.Name, StringComparer.CurrentCultureIgnoreCase))
{
ct.ThrowIfCancellationRequested();
bool guessed = game.ExePath is null;
string? exe = game.ExePath ?? _locator.PickPrimary(game.InstallDirectory);
if (exe is not null)
{
exe = _identity.Normalise(exe);
if (!seen.Add(exe))
{
continue; // the same executable under two stores: one row, the first store's
}
}
// A store's record can outlive the install (a title moved or uninstalled by hand): the review says so
// rather than the import failing later.
bool missing = exe is not null && _identity.Read(exe) is null;
bool already = exe is not null && await _games.FindAsync(exe, ct).ConfigureAwait(false) is { InLibrary: true };
candidates.Add(new ImportCandidate(game, exe, already, guessed, missing));
}
_log($"import: {source.Platform} — {games.Count} title(s)");
}
return candidates;
}
/// <summary>Add the ticked candidates. A row that appeared meanwhile is left as it is; the store's facts are applied either way.</summary>
public async ValueTask<ImportReport> ImportAsync(IReadOnlyList<ImportCandidate> selected, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(selected);
int added = 0;
int skipped = 0;
foreach (ImportCandidate c in selected)
{
ct.ThrowIfCancellationRequested();
if (c.ExePath is null || _identity.Read(c.ExePath) is not { } fingerprint)
{
skipped++;
_log($"import: {c.Game.Name} skipped — no readable executable");
continue;
}
GameRow? before = await _games.FindAsync(c.ExePath, ct).ConfigureAwait(false);
GameRow row = await _games.EnsureAsync(fingerprint, c.Game.Name, ct).ConfigureAwait(false);
_ = await _games.ApplyStoreMetadataAsync(row.Id, new StoreMetadata { Platform = c.Game.Platform, StoreId = c.Game.StoreId, GameVersion = c.Game.Version }, ct).ConfigureAwait(false);
if (before is { InLibrary: true })
{
skipped++;
}
else
{
added++;
_log($"import: added {c.Game.Name} ({c.Game.Platform} {c.Game.StoreId}) — hooking off");
}
}
return new ImportReport(added, skipped);
}
}
@@ -0,0 +1,9 @@
namespace FrameLedger.Application.Import;
/// <summary>
/// One installed title as a store's own records describe it (FR-1.2, P4 PR-4): the platform id in
/// <c>games.platform</c>'s vocabulary, the store's id for it, its display name, where it is installed, the
/// executable when the store names one (GOG and Epic do; Steam and itch do not), and the store's version string.
/// Read from local launcher files and registry keys only — nothing is fetched (CLAUDE.md rule 8).
/// </summary>
public sealed record StoreGame(string Platform, string StoreId, string Name, string InstallDirectory, string? ExePath, string? Version);
@@ -48,4 +48,12 @@ public interface IGameRepository
/// are always written. False when the game does not exist.
/// </summary>
ValueTask<bool> ApplyDetectionAsync(long gameId, DetectionWrite detection, CancellationToken ct = default);
/// <summary>
/// The library import (FR-1.2, P4 PR-4): a store's <c>platform</c>, <c>store_id</c> and version for a game, under
/// the same per-field provenance rule as <see cref="ApplyDetectionAsync"/> — the user's value stays, a badged one
/// is refreshed, an empty one is filled and badged <c>detected</c>. Never a hook column. False when the game
/// does not exist.
/// </summary>
ValueTask<bool> ApplyStoreMetadataAsync(long gameId, StoreMetadata store, CancellationToken ct = default);
}
@@ -0,0 +1,17 @@
namespace FrameLedger.Application.Persistence;
/// <summary>
/// What a store's own records say about a game (FR-1.2, P4 PR-4), persisted through
/// <see cref="IGameRepository.ApplyStoreMetadataAsync"/> under the same provenance rule as detection: a value the
/// user typed is never overwritten, a value a store or a scan wrote before is refreshed, an empty field is filled
/// and badged <c>detected</c>. Null = the store did not say; the field is left as it is.
/// </summary>
public sealed record StoreMetadata
{
/// <summary><c>steam</c> · <c>gog</c> · <c>epic</c> · <c>itch</c>.</summary>
public required string Platform { get; init; }
public string? StoreId { get; init; }
public string? GameVersion { get; init; }
}
@@ -0,0 +1,65 @@
using System.Text.Json;
using FrameLedger.Application.Import;
namespace FrameLedger.Infrastructure.Import;
/// <summary>
/// The Epic Games Launcher's installed library (FR-1.2): one <c>*.item</c> JSON per title under
/// <c>%ProgramData%\Epic\EpicGamesLauncher\Data\Manifests</c> — <c>DisplayName</c>, <c>InstallLocation</c>,
/// <c>LaunchExecutable</c> (relative to the install), <c>AppName</c> (the store id) and <c>AppVersionString</c>.
/// Read with <c>JsonDocument</c> so an unexpected shape costs that one file, never the import.
/// </summary>
public sealed class EpicLibrarySource(string? manifestsDirectory = null) : IStoreLibrarySource
{
public static string DefaultDirectory => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "Epic", "EpicGamesLauncher", "Data", "Manifests");
public string Platform => "epic";
public ValueTask<IReadOnlyList<StoreGame>> ListAsync(CancellationToken ct = default)
{
string dir = manifestsDirectory ?? DefaultDirectory;
if (!Directory.Exists(dir))
{
return ValueTask.FromResult<IReadOnlyList<StoreGame>>([]);
}
List<StoreGame> games = [];
foreach (string item in Directory.EnumerateFiles(dir, "*.item"))
{
ct.ThrowIfCancellationRequested();
if (Read(item) is { } game)
{
games.Add(game);
}
}
return ValueTask.FromResult<IReadOnlyList<StoreGame>>(games);
}
private static StoreGame? Read(string item)
{
try
{
using JsonDocument doc = JsonDocument.Parse(File.ReadAllText(item));
JsonElement root = doc.RootElement;
string? name = Text(root, "DisplayName");
string? location = Text(root, "InstallLocation");
string? id = Text(root, "AppName");
if (name is null || location is null || id is null)
{
return null;
}
string? launch = Text(root, "LaunchExecutable");
string? exe = string.IsNullOrWhiteSpace(launch) ? null : Path.Combine(location, launch);
return new StoreGame("epic", id, name, location, exe, Text(root, "AppVersionString"));
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or JsonException)
{
return null;
}
}
private static string? Text(JsonElement root, string property) =>
root.ValueKind == JsonValueKind.Object && root.TryGetProperty(property, out JsonElement e) && e.ValueKind == JsonValueKind.String ? e.GetString() : null;
}
@@ -0,0 +1,101 @@
using FrameLedger.Application.Import;
namespace FrameLedger.Infrastructure.Import;
/// <summary>
/// <see cref="IExecutableLocator"/> for the stores that do not name the game's executable (Steam, itch): walk the
/// install directory three levels deep, drop the helpers a game ships beside itself (crash handlers, installers,
/// redistributables, anti-cheat services, launchers' own updaters), and take the largest of what is left — a
/// shipping Unreal or Unity binary dwarfs its neighbours. A guess the review list shows; the user unticks what is
/// wrong. Never launched, never read past its size.
/// </summary>
public sealed class ExecutableLocator : IExecutableLocator
{
public const int MaxDepth = 3;
/// <summary>Name fragments of the helpers a game ships beside itself; a file whose name carries one is never the game.</summary>
public static readonly IReadOnlyList<string> HelperFragments =
[
"crash", "handler", "unins", "setup", "install", "redist", "vc_redist", "dxsetup", "dotnet", "cef", "report", "updater",
"launcher_helper", "easyanticheat", "beservice", "battleye", "steamerrorreporter", "ue4prereq", "uecc", "vcredist", "python", "node",
];
public static bool IsHelper(string fileNameWithoutExtension)
{
ArgumentNullException.ThrowIfNull(fileNameWithoutExtension);
foreach (string fragment in HelperFragments)
{
if (fileNameWithoutExtension.Contains(fragment, StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
return false;
}
public string? PickPrimary(string installDirectory)
{
ArgumentException.ThrowIfNullOrWhiteSpace(installDirectory);
if (!Directory.Exists(installDirectory))
{
return null;
}
string? best = null;
long bestSize = -1;
foreach (string exe in Walk(installDirectory, 0))
{
if (IsHelper(Path.GetFileNameWithoutExtension(exe)))
{
continue;
}
long size;
try
{
size = new FileInfo(exe).Length;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
continue;
}
if (size > bestSize)
{
best = exe;
bestSize = size;
}
}
return best;
}
private static IEnumerable<string> Walk(string dir, int depth)
{
IEnumerable<string> files;
IEnumerable<string> dirs;
try
{
files = Directory.EnumerateFiles(dir, "*.exe");
dirs = depth < MaxDepth ? Directory.EnumerateDirectories(dir) : [];
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
yield break;
}
foreach (string f in files)
{
yield return f;
}
foreach (string d in dirs)
{
foreach (string f in Walk(d, depth + 1))
{
yield return f;
}
}
}
}
@@ -0,0 +1,58 @@
using FrameLedger.Application.Import;
using Microsoft.Win32;
namespace FrameLedger.Infrastructure.Import;
/// <summary>
/// GOG Galaxy's installed library (FR-1.2): one subkey per title under
/// <c>HKLM\SOFTWARE\WOW6432Node\GOG.com\Games</c> — the subkey name is the store id; <c>gameName</c>, <c>path</c>,
/// <c>exe</c> (the launch executable's full path) and <c>ver</c> are its values. Read-only, whichever hive and key
/// the caller names (a test uses its own HKCU key); a key that is not there is an empty library.
/// </summary>
public sealed class GogLibrarySource(RegistryHive hive = RegistryHive.LocalMachine, string keyPath = GogLibrarySource.DefaultKeyPath) : IStoreLibrarySource
{
public const string DefaultKeyPath = @"SOFTWARE\WOW6432Node\GOG.com\Games";
public string Platform => "gog";
public ValueTask<IReadOnlyList<StoreGame>> ListAsync(CancellationToken ct = default)
{
List<StoreGame> games = [];
try
{
using RegistryKey baseKey = RegistryKey.OpenBaseKey(hive, RegistryView.Default);
using RegistryKey? root = baseKey.OpenSubKey(keyPath, writable: false);
if (root is null)
{
return ValueTask.FromResult<IReadOnlyList<StoreGame>>([]);
}
foreach (string id in root.GetSubKeyNames())
{
ct.ThrowIfCancellationRequested();
using RegistryKey? game = root.OpenSubKey(id, writable: false);
if (game is null)
{
continue;
}
string? name = game.GetValue("gameName") as string;
string? path = game.GetValue("path") as string;
if (string.IsNullOrWhiteSpace(name) || string.IsNullOrWhiteSpace(path))
{
continue;
}
string? exe = game.GetValue("exe") as string;
games.Add(new StoreGame("gog", id, name, path, string.IsNullOrWhiteSpace(exe) ? null : exe, game.GetValue("ver") as string));
}
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or System.Security.SecurityException)
{
// A hive we may not read is an empty library, not a failed import.
return ValueTask.FromResult<IReadOnlyList<StoreGame>>([]);
}
return ValueTask.FromResult<IReadOnlyList<StoreGame>>(games);
}
}
@@ -0,0 +1,67 @@
using System.IO.Compression;
using System.Text.Json;
using FrameLedger.Application.Import;
namespace FrameLedger.Infrastructure.Import;
/// <summary>
/// itch.io's installed library (FR-1.2): every install under <c>%APPDATA%\itch\apps</c> carries
/// <c>.itch\receipt.json.gz</c> — gzipped JSON whose <c>game</c> object names <c>title</c> and <c>id</c>. The receipt
/// does not say which executable is the game, so the locator guesses. A receipt that will not gunzip or parse
/// costs that one install.
/// </summary>
public sealed class ItchLibrarySource(string? appsDirectory = null) : IStoreLibrarySource
{
public static string DefaultDirectory => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "itch", "apps");
public string Platform => "itch";
public ValueTask<IReadOnlyList<StoreGame>> ListAsync(CancellationToken ct = default)
{
string dir = appsDirectory ?? DefaultDirectory;
if (!Directory.Exists(dir))
{
return ValueTask.FromResult<IReadOnlyList<StoreGame>>([]);
}
List<StoreGame> games = [];
foreach (string install in Directory.EnumerateDirectories(dir))
{
ct.ThrowIfCancellationRequested();
string receipt = Path.Combine(install, ".itch", "receipt.json.gz");
if (File.Exists(receipt) && Read(receipt, install) is { } game)
{
games.Add(game);
}
}
return ValueTask.FromResult<IReadOnlyList<StoreGame>>(games);
}
private static StoreGame? Read(string receipt, string install)
{
try
{
using FileStream file = File.OpenRead(receipt);
using var gzip = new GZipStream(file, CompressionMode.Decompress);
using JsonDocument doc = JsonDocument.Parse(gzip);
if (!doc.RootElement.TryGetProperty("game", out JsonElement game) || game.ValueKind != JsonValueKind.Object)
{
return null;
}
string? title = game.TryGetProperty("title", out JsonElement t) && t.ValueKind == JsonValueKind.String ? t.GetString() : null;
string? id = game.TryGetProperty("id", out JsonElement i) ? i.ValueKind switch
{
JsonValueKind.Number => i.GetRawText(),
JsonValueKind.String => i.GetString(),
_ => null,
} : null;
return title is null || id is null ? null : new StoreGame("itch", id, title, install, ExePath: null, Version: null);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or JsonException or InvalidDataException)
{
return null;
}
}
}
@@ -0,0 +1,18 @@
namespace FrameLedger.Infrastructure.Import;
/// <summary>A block: string values or nested blocks under case-insensitive keys.</summary>
public sealed class KeyValuesBlock
{
private readonly Dictionary<string, object> _entries = new(StringComparer.OrdinalIgnoreCase);
public IReadOnlyDictionary<string, object> Entries => _entries;
public string? Value(string key) => _entries.TryGetValue(key, out object? v) && v is string s ? s : null;
public KeyValuesBlock? Child(string key) => _entries.TryGetValue(key, out object? v) && v is KeyValuesBlock b ? b : null;
/// <summary>Every nested block, in file order.</summary>
public IEnumerable<KeyValuePair<string, KeyValuesBlock>> Children => _entries.Where(static e => e.Value is KeyValuesBlock).Select(static e => new KeyValuePair<string, KeyValuesBlock>(e.Key, (KeyValuesBlock)e.Value));
internal void Set(string key, object value) => _entries[key] = value;
}
@@ -0,0 +1,111 @@
using FrameLedger.Application.Import;
using Microsoft.Win32;
namespace FrameLedger.Infrastructure.Import;
/// <summary>
/// Steam's installed library (FR-1.2): <c>steamapps\libraryfolders.vdf</c> names every library folder, and each
/// folder's <c>steamapps\appmanifest_&lt;appid&gt;.acf</c> names one installed title — <c>appid</c>, <c>name</c>,
/// <c>installdir</c> (under <c>steamapps\common</c>), <c>buildid</c>. Steam does not record which executable is the
/// game, so <see cref="StoreGame.ExePath"/> is null and the locator guesses. The Steam root comes from
/// <c>HKCU\Software\Valve\Steam\SteamPath</c> unless a test hands one in.
/// </summary>
public sealed class SteamLibrarySource(string? steamRoot = null) : IStoreLibrarySource
{
public string Platform => "steam";
public ValueTask<IReadOnlyList<StoreGame>> ListAsync(CancellationToken ct = default)
{
string? root = steamRoot ?? InstalledRoot();
if (root is null || !Directory.Exists(root))
{
return ValueTask.FromResult<IReadOnlyList<StoreGame>>([]);
}
List<StoreGame> games = [];
foreach (string library in Libraries(root))
{
ct.ThrowIfCancellationRequested();
string steamapps = Path.Combine(library, "steamapps");
if (!Directory.Exists(steamapps))
{
continue;
}
foreach (string manifest in Directory.EnumerateFiles(steamapps, "appmanifest_*.acf"))
{
if (ReadManifest(manifest, steamapps) is { } game)
{
games.Add(game);
}
}
}
return ValueTask.FromResult<IReadOnlyList<StoreGame>>(games);
}
/// <summary>The root itself plus every <c>path</c> in <c>libraryfolders.vdf</c> (both its old and new shapes name the folder as <c>path</c>).</summary>
private static HashSet<string> Libraries(string root)
{
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { Path.GetFullPath(root) };
string vdf = Path.Combine(root, "steamapps", "libraryfolders.vdf");
if (TryRead(vdf) is { } text)
{
KeyValuesBlock parsed = ValveKeyValues.Parse(text);
KeyValuesBlock folders = parsed.Child("libraryfolders") ?? parsed;
foreach ((_, KeyValuesBlock entry) in folders.Children)
{
if (entry.Value("path") is { Length: > 0 } path)
{
seen.Add(Path.GetFullPath(path));
}
}
}
return seen;
}
private static StoreGame? ReadManifest(string manifest, string steamapps)
{
if (TryRead(manifest) is not { } text)
{
return null;
}
KeyValuesBlock state = ValveKeyValues.Parse(text).Child("AppState") ?? ValveKeyValues.Parse(text);
string? appId = state.Value("appid");
string? name = state.Value("name");
string? installDir = state.Value("installdir");
if (appId is null || name is null || installDir is null)
{
return null;
}
return new StoreGame("steam", appId, name, Path.Combine(steamapps, "common", installDir), ExePath: null, state.Value("buildid"));
}
private static string? InstalledRoot()
{
try
{
using RegistryKey? key = Registry.CurrentUser.OpenSubKey(@"Software\Valve\Steam", writable: false);
return key?.GetValue("SteamPath") as string is { Length: > 0 } path ? Path.GetFullPath(path) : null;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or System.Security.SecurityException)
{
return null;
}
}
private static string? TryRead(string path)
{
try
{
return File.Exists(path) ? File.ReadAllText(path) : null;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
return null;
}
}
}
@@ -0,0 +1,141 @@
using System.Text;
namespace FrameLedger.Infrastructure.Import;
/// <summary>
/// Valve's text KeyValues format (<c>libraryfolders.vdf</c>, <c>appmanifest_*.acf</c>), read into nested dictionaries:
/// <c>"key" "value"</c> pairs and <c>"key" { … }</c> blocks, quoted or bare tokens, <c>//</c> comments, the
/// escapes <c>\"</c> <c>\\</c> <c>\n</c> <c>\t</c>. Keys compare case-insensitively (Steam writes <c>AppState</c>
/// and <c>appid</c> in whatever case it likes). Malformed input yields what parsed up to the fault, never an
/// exception — a launcher file is untrusted input to this process (P4 PR-4).
/// </summary>
public static class ValveKeyValues
{
public static KeyValuesBlock Parse(string text)
{
ArgumentNullException.ThrowIfNull(text);
var root = new KeyValuesBlock();
int pos = 0;
ParseInto(root, text, ref pos, depth: 0);
return root;
}
private static void ParseInto(KeyValuesBlock block, string text, ref int pos, int depth)
{
while (true)
{
string? key = NextToken(text, ref pos, out bool closing);
if (key is null || closing)
{
return;
}
string? value = NextToken(text, ref pos, out bool _, out bool opening);
if (opening)
{
var child = new KeyValuesBlock();
if (depth < 32)
{
ParseInto(child, text, ref pos, depth + 1);
}
block.Set(key, child);
}
else if (value is not null)
{
block.Set(key, value);
}
else
{
return;
}
}
}
private static string? NextToken(string text, ref int pos, out bool closing) => NextToken(text, ref pos, out closing, out _);
private static string? NextToken(string text, ref int pos, out bool closing, out bool opening)
{
closing = false;
opening = false;
while (pos < text.Length)
{
char c = text[pos];
if (char.IsWhiteSpace(c))
{
pos++;
}
else if (c == '/' && pos + 1 < text.Length && text[pos + 1] == '/')
{
while (pos < text.Length && text[pos] != '\n')
{
pos++;
}
}
else
{
break;
}
}
if (pos >= text.Length)
{
return null;
}
switch (text[pos])
{
case '{':
pos++;
opening = true;
return string.Empty;
case '}':
pos++;
closing = true;
return string.Empty;
case '"':
return Quoted(text, ref pos);
default:
int start = pos;
while (pos < text.Length && !char.IsWhiteSpace(text[pos]) && text[pos] != '{' && text[pos] != '}')
{
pos++;
}
return text[start..pos];
}
}
private static string Quoted(string text, ref int pos)
{
var sb = new StringBuilder();
pos++; // the opening quote
while (pos < text.Length)
{
char c = text[pos++];
if (c == '"')
{
return sb.ToString();
}
if (c == '\\' && pos < text.Length)
{
char e = text[pos++];
sb.Append(e switch
{
'n' => '\n',
't' => '\t',
'"' => '"',
'\\' => '\\',
_ => e,
});
}
else
{
sb.Append(c);
}
}
return sb.ToString(); // unterminated: what was read
}
}
@@ -54,6 +54,10 @@ public sealed class SqliteGameRepository : IGameRepository
private const string _delete = "DELETE FROM games WHERE id = @id";
private const string _applyStore =
"UPDATE games SET platform = @platform, store_id = @storeId, game_version = @gameVersion, field_provenance = @provenance, "
+ "updated_at = @now WHERE id = @id";
private const string _applyDetection =
"UPDATE games SET engine = @engine, engine_version = @engineVersion, platform = @platform, capability_flags = @flags, "
+ "field_provenance = @provenance, detection_rules_version = @rules, detection_exe_size_bytes = @size, detection_exe_mtime_ms = @mtime, "
@@ -213,6 +217,41 @@ public sealed class SqliteGameRepository : IGameRepository
}, ct);
}
public ValueTask<bool> ApplyStoreMetadataAsync(long gameId, StoreMetadata store, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(store);
if (!GameMetadata.Platforms.Contains(store.Platform, StringComparer.Ordinal) || string.Equals(store.Platform, "none", StringComparison.Ordinal))
{
throw new ArgumentException($"'{store.Platform}' is not a store (steam|gog|epic|itch)", nameof(store));
}
return _db.WriteAsync(async (c, tx, token) =>
{
GameRow? before = await SqliteReaders.ReadOneAsync(c, new CommandDefinition(_selectById, new { id = gameId }, tx, cancellationToken: token), Read).ConfigureAwait(false);
if (before is null)
{
return false;
}
// The same rule as a detection write (05_DETECTION §Caching): the user's value stays, a badged one is
// refreshed, an empty one is filled and badged. A store's facts are detected facts, not the user's.
Dictionary<string, string> map = FieldProvenance.Parse(before.FieldProvenanceJson);
string platform = FieldProvenance.Resolve(map, "platform", string.Equals(before.Platform, "none", StringComparison.Ordinal) ? null : before.Platform, store.Platform) ?? "none";
string? storeId = FieldProvenance.Resolve(map, "store_id", before.StoreId, store.StoreId);
string? gameVersion = FieldProvenance.Resolve(map, "game_version", before.GameVersion, store.GameVersion);
var p = new
{
id = gameId,
platform,
storeId,
gameVersion,
provenance = map.Count == 0 ? before.FieldProvenanceJson : JsonSerializer.Serialize(map, LedgerJsonContext.Default.DictionaryStringString),
now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
};
return await c.ExecuteAsync(new CommandDefinition(_applyStore, p, tx, cancellationToken: token)).ConfigureAwait(false) == 1;
}, ct);
}
private static Task<GameRow?> ReadByPathAsync(SqliteConnection c, SqliteTransaction? tx, string path, CancellationToken ct) =>
SqliteReaders.ReadOneAsync(c, new CommandDefinition(_selectByPath, new { path }, tx, cancellationToken: ct), Read);
@@ -0,0 +1,149 @@
using System.IO;
using FluentAssertions;
using FrameLedger.App.Pages;
using FrameLedger.App.Services;
using FrameLedger.App.ViewModels;
using FrameLedger.Application.Import;
using FrameLedger.Application.Persistence;
using FrameLedger.Infrastructure.Import;
using FrameLedger.Infrastructure.Watch;
namespace FrameLedger.App.Tests;
/// <summary>
/// File ▸ Import library… end to end over a scratch ledger and real files (P4 PR-4): a store's titles reach the
/// review, the ticked ones land as rows with hooking off and the store's facts, the Games page is shown; nothing found
/// or a cancel adds nothing. And the review's own bookkeeping: the count follows the ticks, select-all skips what
/// cannot be imported.
/// </summary>
public sealed class ImportLibraryFlowTests : IDisposable
{
private readonly string _dir = Path.Combine(Path.GetTempPath(), "fl-import-" + Guid.NewGuid().ToString("N"));
public ImportLibraryFlowTests() => Directory.CreateDirectory(_dir);
public void Dispose() => Directory.Delete(_dir, recursive: true);
private static CancellationToken Ct => TestContext.Current.CancellationToken;
private sealed class ScriptedStore(params StoreGame[] games) : IStoreLibrarySource
{
public string Platform => "epic";
public ValueTask<IReadOnlyList<StoreGame>> ListAsync(CancellationToken ct = default) => ValueTask.FromResult<IReadOnlyList<StoreGame>>(games);
}
private sealed class ScriptedReview(Func<IReadOnlyList<ImportCandidate>, IReadOnlyList<ImportCandidate>?> answer) : IImportReview
{
public List<IReadOnlyList<ImportCandidate>> Shown { get; } = [];
public Task<IReadOnlyList<ImportCandidate>?> ReviewAsync(IReadOnlyList<ImportCandidate> candidates, CancellationToken ct = default)
{
Shown.Add(candidates);
return Task.FromResult(answer(candidates));
}
}
private sealed class RecordingStrip : IMessageStrip
{
public List<string> Kinds { get; } = [];
public void Info(string title, string body) => Kinds.Add("info");
public void Success(string title, string body) => Kinds.Add("success");
public void Warn(string title, string body) => Kinds.Add("warn");
}
private sealed class FakeNavigator : IPageNavigator
{
public List<string> Pages { get; } = [];
public void Navigate<TPage>()
where TPage : class => Pages.Add(typeof(TPage).Name);
public void GoBack() => Pages.Add("back");
}
private async Task<string> ExeAsync(string name)
{
string dir = Path.Combine(_dir, name);
Directory.CreateDirectory(dir);
string exe = Path.Combine(dir, name + ".exe");
await File.WriteAllBytesAsync(exe, new byte[64], Ct).ConfigureAwait(false);
return exe;
}
[Fact]
public async Task TheTickedTitlesLandWithHookingOffAndTheStoresFacts()
{
await using ScratchLedger s = await ScratchLedger.OpenAsync();
string alan = await ExeAsync("AlanWake2");
string fort = await ExeAsync("Fortnite");
var store = new ScriptedStore(
new StoreGame("epic", "aw2", "Alan Wake 2", Path.GetDirectoryName(alan)!, alan, "1.2.3"),
new StoreGame("epic", "fn", "Fortnite", Path.GetDirectoryName(fort)!, fort, null),
new StoreGame("epic", "gone", "Uninstalled", Path.Combine(_dir, "gone"), Path.Combine(_dir, "gone", "gone.exe"), null));
var review = new ScriptedReview(static c => [.. c.Where(static x => string.Equals(x.Game.StoreId, "aw2", StringComparison.Ordinal))]);
var strip = new RecordingStrip();
var nav = new FakeNavigator();
var importer = new LibraryImporter([store], s.Games, new ExecutableIdentitySource(), new ExecutableLocator(), static _ => { });
var flow = new ImportLibraryFlow(importer, review, strip, nav);
ImportReport? report = await flow.RunAsync(Ct);
report.Should().NotBeNull();
report!.Added.Should().Be(1);
review.Shown.Should().ContainSingle().Which.Should().HaveCount(3, "every title the store named reaches the review, importable or not");
review.Shown[0].Single(static c => string.Equals(c.Game.StoreId, "gone", StringComparison.Ordinal)).CanImport.Should().BeFalse("its executable is not on disk");
GameRow row = (await s.Games.ListAsync(Ct)).Should().ContainSingle().Subject;
row.Name.Should().Be("Alan Wake 2");
row.HookEnabled.Should().BeFalse("FR-1.2: import never enables hooking");
row.Platform.Should().Be("epic");
row.StoreId.Should().Be("aw2");
row.GameVersion.Should().Be("1.2.3");
strip.Kinds.Should().Equal("success");
nav.Pages.Should().Equal(nameof(GamesPage));
}
[Fact]
public async Task NothingFoundOrACancelAddsNothing()
{
await using ScratchLedger s = await ScratchLedger.OpenAsync();
var strip = new RecordingStrip();
var nav = new FakeNavigator();
var review = new ScriptedReview(static _ => null);
var empty = new ImportLibraryFlow(new LibraryImporter([new ScriptedStore()], s.Games, new ExecutableIdentitySource(), new ExecutableLocator(), static _ => { }), review, strip, nav);
(await empty.RunAsync(Ct)).Should().BeNull();
strip.Kinds.Should().Equal("info");
review.Shown.Should().BeEmpty("nothing to review");
string exe = await ExeAsync("Game");
var cancelled = new ImportLibraryFlow(new LibraryImporter([new ScriptedStore(new StoreGame("epic", "g", "Game", Path.GetDirectoryName(exe)!, exe, null))], s.Games, new ExecutableIdentitySource(), new ExecutableLocator(), static _ => { }), review, strip, nav);
(await cancelled.RunAsync(Ct)).Should().BeNull();
(await s.Games.ListAsync(Ct)).Should().BeEmpty();
nav.Pages.Should().BeEmpty();
}
[Fact]
public void TheReviewCountsTicksAndSelectAllSkipsWhatCannotBeImported()
{
var can = new ImportCandidate(new StoreGame("steam", "1", "A", @"C:\a", @"C:\a\a.exe", null), @"C:\a\a.exe", AlreadyInLibrary: false, ExecutableGuessed: true);
var already = new ImportCandidate(new StoreGame("steam", "2", "B", @"C:\b", @"C:\b\b.exe", null), @"C:\b\b.exe", AlreadyInLibrary: true, ExecutableGuessed: false);
var none = new ImportCandidate(new StoreGame("steam", "3", "C", @"C:\c", null, null), null, AlreadyInLibrary: false, ExecutableGuessed: true);
var vm = new ImportReviewViewModel([can, already, none]);
vm.SelectedCount.Should().Be(1, "only the importable row is ticked by default");
vm.CanImport.Should().BeTrue();
vm.Rows[1].Note.Should().Be(Strings.Import_Note_Already);
vm.Rows[2].Note.Should().Be(Strings.Import_Note_NoExe);
vm.Rows[0].Note.Should().Be(Strings.Import_Note_Guessed);
vm.SelectNoneCommand.Execute(null);
vm.SelectedCount.Should().Be(0);
vm.CanImport.Should().BeFalse();
vm.SelectAllCommand.Execute(null);
vm.SelectedCount.Should().Be(1);
vm.Selected.Should().ContainSingle().Which.Should().Be(can);
}
}
@@ -0,0 +1,116 @@
using FluentAssertions;
using FrameLedger.Application.Import;
using FrameLedger.Application.Persistence;
using FrameLedger.Application.Tests.Recording;
using FrameLedger.Application.Watch;
using FrameLedger.Domain.Consent;
namespace FrameLedger.Application.Tests.Import;
/// <summary>
/// FR-1.2 (P4 PR-4): discovery joins every store's titles to the ledger — the store's executable where it names one,
/// the locator's guess where it does not, "already in the library" where the row exists, no executable where none
/// is found — and the import adds exactly the ticked rows, hooking off, with the store's facts applied. A store that
/// throws costs its own titles, never the others'.
/// </summary>
public sealed class LibraryImporterTests
{
private static CancellationToken Ct => TestContext.Current.CancellationToken;
private sealed class ScriptedStore(string platform, params StoreGame[] games) : IStoreLibrarySource
{
public bool Throws { get; set; }
public string Platform => platform;
public ValueTask<IReadOnlyList<StoreGame>> ListAsync(CancellationToken ct = default) =>
Throws ? throw new IOException("launcher files unreadable") : ValueTask.FromResult<IReadOnlyList<StoreGame>>(games);
}
private sealed class FakeIdentity : IExecutableIdentitySource
{
public HashSet<string> Existing { get; } = new(StringComparer.OrdinalIgnoreCase);
public ExecutableFingerprint? Read(string normalisedExePath) =>
Existing.Contains(normalisedExePath) ? new ExecutableFingerprint { ExePath = normalisedExePath, SizeBytes = 7, MtimeUnixMs = 7 } : null;
public string Normalise(string exePath) => exePath.ToUpperInvariant();
}
private sealed class FakeLocator : IExecutableLocator
{
public Dictionary<string, string?> Guesses { get; } = new(StringComparer.OrdinalIgnoreCase);
public string? PickPrimary(string installDirectory) => Guesses.GetValueOrDefault(installDirectory);
}
[Fact]
public async Task DiscoveryJoinsTheStoresToTheLedgerAndImportAddsOnlyWhatWasTicked()
{
var games = new FakeGameRepository();
var identity = new FakeIdentity();
var locator = new FakeLocator();
List<string> log = [];
var steam = new ScriptedStore("steam",
new StoreGame("steam", "1091500", "Cyberpunk 2077", @"D:\Steam\steamapps\common\Cyberpunk 2077", null, "15877371"),
new StoreGame("steam", "2358720", "Wukong", @"D:\Steam\steamapps\common\BlackMythWukong", null, null));
var gog = new ScriptedStore("gog", new StoreGame("gog", "1207658924", "The Witcher 3", @"D:\GOG\W3", @"D:\GOG\W3\bin\witcher3.exe", "4.04"));
locator.Guesses[@"D:\Steam\steamapps\common\Cyberpunk 2077"] = @"D:\Steam\steamapps\common\Cyberpunk 2077\bin\x64\Cyberpunk2077.exe";
identity.Existing.Add(@"D:\STEAM\STEAMAPPS\COMMON\CYBERPUNK 2077\BIN\X64\CYBERPUNK2077.EXE");
identity.Existing.Add(@"D:\GOG\W3\BIN\WITCHER3.EXE");
// The Witcher is already in the library, added by hand.
await games.EnsureAsync(new ExecutableFingerprint { ExePath = @"D:\GOG\W3\BIN\WITCHER3.EXE", SizeBytes = 1, MtimeUnixMs = 1 }, "witcher3", Ct);
var importer = new LibraryImporter([steam, gog], games, identity, locator, log.Add);
IReadOnlyList<ImportCandidate> found = await importer.DiscoverAsync(Ct);
found.Should().HaveCount(3);
ImportCandidate cp = found.Single(static c => string.Equals(c.Game.StoreId, "1091500", StringComparison.Ordinal));
cp.ExePath.Should().Be(@"D:\STEAM\STEAMAPPS\COMMON\CYBERPUNK 2077\BIN\X64\CYBERPUNK2077.EXE", "the locator's guess, normalised");
cp.ExecutableGuessed.Should().BeTrue();
cp.CanImport.Should().BeTrue();
ImportCandidate wukong = found.Single(static c => string.Equals(c.Game.StoreId, "2358720", StringComparison.Ordinal));
wukong.ExePath.Should().BeNull("nothing found under its install directory");
wukong.CanImport.Should().BeFalse();
ImportCandidate w3 = found.Single(static c => string.Equals(c.Game.StoreId, "1207658924", StringComparison.Ordinal));
w3.ExecutableGuessed.Should().BeFalse("GOG named it");
w3.AlreadyInLibrary.Should().BeTrue();
w3.CanImport.Should().BeFalse();
ImportReport report = await importer.ImportAsync([cp, w3], Ct);
report.Added.Should().Be(1);
report.Skipped.Should().Be(1, "the Witcher was already there — left as it was, its store facts applied");
GameRow added = games.Rows[cp.ExePath!];
added.Name.Should().Be("Cyberpunk 2077", "the store's name, not the exe's");
added.HookEnabled.Should().BeFalse("import never enables hooking — FR-1.2");
added.Platform.Should().Be("steam");
added.StoreId.Should().Be("1091500");
added.GameVersion.Should().Be("15877371");
games.Stores.Should().HaveCount(2);
games.Rows.Should().HaveCount(2);
log.Should().Contain(static l => l.Contains("added Cyberpunk 2077", StringComparison.Ordinal) && l.Contains("hooking off", StringComparison.Ordinal));
}
[Fact]
public async Task AStoreThatThrowsCostsItsOwnTitlesAndTheSameExecutableUnderTwoStoresIsOneRow()
{
var games = new FakeGameRepository();
var identity = new FakeIdentity();
var locator = new FakeLocator();
List<string> log = [];
var epic = new ScriptedStore("epic", new StoreGame("epic", "e1", "Shared", @"D:\G\Shared", @"D:\G\Shared\game.exe", null)) { Throws = true };
var gog = new ScriptedStore("gog", new StoreGame("gog", "g1", "Shared", @"D:\G\Shared", @"D:\G\Shared\game.exe", "1.0"));
var itch = new ScriptedStore("itch", new StoreGame("itch", "i1", "Shared again", @"D:\G\Shared", @"D:\G\Shared\GAME.EXE", null));
IReadOnlyList<ImportCandidate> found = await new LibraryImporter([epic, gog, itch], games, identity, locator, log.Add).DiscoverAsync(Ct);
found.Should().ContainSingle().Which.Game.Platform.Should().Be("gog", "epic threw and itch named the same executable, so the first store to name it keeps it");
log.Should().Contain(static l => l.StartsWith("import: epic library unreadable", StringComparison.Ordinal));
ImportReport report = await new LibraryImporter([gog], games, identity, locator, log.Add).ImportAsync(found, Ct);
report.Added.Should().Be(0);
report.Skipped.Should().Be(1, "the executable is not on disk, so nothing can be fingerprinted or added");
games.Rows.Should().BeEmpty();
}
}
@@ -67,6 +67,26 @@ internal sealed class FakeGameRepository : IGameRepository
public ValueTask<bool> RemoveAsync(long gameId, bool keepSessions, CancellationToken ct = default) => throw new NotSupportedException();
/// <summary>Every store write, in order (P4 PR-4); the row takes the store's platform, id and version whole (the SQLite adapter's provenance rule has its own tests).</summary>
public List<(long GameId, StoreMetadata Store)> Stores { get; } = [];
public ValueTask<bool> ApplyStoreMetadataAsync(long gameId, StoreMetadata store, CancellationToken ct = default)
{
Stores.Add((gameId, store));
foreach ((string key, GameRow row) in Rows)
{
if (row.Id != gameId)
{
continue;
}
Rows[key] = row with { Platform = store.Platform, StoreId = store.StoreId ?? row.StoreId, GameVersion = store.GameVersion ?? row.GameVersion };
return ValueTask.FromResult(true);
}
return ValueTask.FromResult(false);
}
/// <summary>Every detection write, in order (P4 PR-1); the row gains the cache key and the flags so a second sweep sees it as current.</summary>
public List<(long GameId, DetectionWrite Write)> Detections { get; } = [];
@@ -0,0 +1,154 @@
using System.IO.Compression;
using System.Text;
using FluentAssertions;
using FrameLedger.Application.Import;
using FrameLedger.Infrastructure.Import;
using Microsoft.Win32;
namespace FrameLedger.Infrastructure.Tests.Import;
/// <summary>
/// The four stores' readers over fixtures written by the test (P4 PR-4): Steam's two-file shape across two library
/// folders, GOG's registry keys under a test key, Epic's <c>.item</c> manifests, itch's gzipped receipts — and the
/// executable locator's guess. A store that is not there is an empty list; a file that will not parse costs one entry.
/// </summary>
public sealed class StoreLibrarySourcesTests : IDisposable
{
private readonly string _dir = Path.Combine(Path.GetTempPath(), "fl-stores-" + Guid.NewGuid().ToString("N"));
public StoreLibrarySourcesTests() => Directory.CreateDirectory(_dir);
public void Dispose() => Directory.Delete(_dir, recursive: true);
private static CancellationToken Ct => TestContext.Current.CancellationToken;
private string Sub(params string[] parts)
{
string p = Path.Combine([_dir, .. parts]);
Directory.CreateDirectory(p);
return p;
}
[Fact]
public async Task SteamListsEveryManifestInEveryLibraryFolderAndNamesNoExecutable()
{
string root = Sub("Steam");
string second = Sub("Library2");
string rootApps = Sub("Steam", "steamapps");
string secondApps = Sub("Library2", "steamapps");
await File.WriteAllTextAsync(Path.Combine(rootApps, "libraryfolders.vdf"),
"\"libraryfolders\"\n{\n\t\"0\"\n\t{\n\t\t\"path\"\t\t\"" + root.Replace("\\", "\\\\", StringComparison.Ordinal) + "\"\n\t}\n\t\"1\"\n\t{\n\t\t\"path\"\t\t\"" + second.Replace("\\", "\\\\", StringComparison.Ordinal) + "\"\n\t}\n}\n", Ct);
await File.WriteAllTextAsync(Path.Combine(rootApps, "appmanifest_1091500.acf"),
"\"AppState\"\n{\n\t\"appid\"\t\t\"1091500\"\n\t\"name\"\t\t\"Cyberpunk 2077\"\n\t\"installdir\"\t\t\"Cyberpunk 2077\"\n\t\"buildid\"\t\t\"15877371\"\n}\n", Ct);
await File.WriteAllTextAsync(Path.Combine(secondApps, "appmanifest_2358720.acf"),
"\"AppState\"\n{\n\t\"appid\"\t\t\"2358720\"\n\t\"name\"\t\t\"Black Myth: Wukong\"\n\t\"installdir\"\t\t\"BlackMythWukong\"\n}\n", Ct);
await File.WriteAllTextAsync(Path.Combine(secondApps, "appmanifest_bad.acf"), "not key values at all {", Ct);
IReadOnlyList<StoreGame> games = await new SteamLibrarySource(root).ListAsync(Ct);
games.Should().HaveCount(2, "the malformed manifest costs one entry, not the library");
StoreGame cp = games.Single(static g => string.Equals(g.StoreId, "1091500", StringComparison.Ordinal));
cp.Platform.Should().Be("steam");
cp.Name.Should().Be("Cyberpunk 2077");
cp.InstallDirectory.Should().Be(Path.Combine(rootApps, "common", "Cyberpunk 2077"));
cp.Version.Should().Be("15877371");
cp.ExePath.Should().BeNull("Steam does not say which executable is the game");
games.Single(static g => string.Equals(g.StoreId, "2358720", StringComparison.Ordinal)).InstallDirectory.Should().StartWith(secondApps);
(await new SteamLibrarySource(Path.Combine(_dir, "nowhere")).ListAsync(Ct)).Should().BeEmpty();
}
[Fact]
public async Task GogReadsItsRegistryKeysUnderWhateverKeyItIsGiven()
{
string own = @"SOFTWARE\FrameLedger.Test\" + Guid.NewGuid().ToString("N");
string key = own + @"\GOG.com\Games";
try
{
using (RegistryKey games = Registry.CurrentUser.CreateSubKey(key + @"\1207658924", writable: true))
{
games.SetValue("gameName", "The Witcher 3");
games.SetValue("path", @"D:\GOG Galaxy\Games\The Witcher 3");
games.SetValue("exe", @"D:\GOG Galaxy\Games\The Witcher 3\bin\x64\witcher3.exe");
games.SetValue("ver", "4.04");
}
using (RegistryKey broken = Registry.CurrentUser.CreateSubKey(key + @"\9999", writable: true))
{
broken.SetValue("gameName", "no path");
}
IReadOnlyList<StoreGame> list = await new GogLibrarySource(RegistryHive.CurrentUser, key).ListAsync(Ct);
StoreGame w3 = list.Should().ContainSingle().Subject;
w3.Platform.Should().Be("gog");
w3.StoreId.Should().Be("1207658924");
w3.Name.Should().Be("The Witcher 3");
w3.ExePath.Should().Be(@"D:\GOG Galaxy\Games\The Witcher 3\bin\x64\witcher3.exe", "GOG names the launch executable");
w3.Version.Should().Be("4.04");
(await new GogLibrarySource(RegistryHive.CurrentUser, key + @"\absent").ListAsync(Ct)).Should().BeEmpty();
}
finally
{
// Only this test's subtree: FrameLedger.Test is shared with VkLayerRegistrationTests, which may be running.
Registry.CurrentUser.DeleteSubKeyTree(own, throwOnMissingSubKey: false);
}
}
[Fact]
public async Task EpicReadsItemManifestsAndItchReadsGzippedReceipts()
{
string manifests = Sub("Manifests");
await File.WriteAllTextAsync(Path.Combine(manifests, "A1.item"),
"{\"DisplayName\":\"Alan Wake 2\",\"InstallLocation\":\"D:\\\\Epic Games\\\\AlanWake2\",\"LaunchExecutable\":\"AlanWake2.exe\",\"AppName\":\"dcbb1ebd\",\"AppVersionString\":\"1.2.3\"}", Ct);
await File.WriteAllTextAsync(Path.Combine(manifests, "B2.item"), "{\"DisplayName\":\"No location\"}", Ct);
await File.WriteAllTextAsync(Path.Combine(manifests, "C3.item"), "{ not json", Ct);
IReadOnlyList<StoreGame> epic = await new EpicLibrarySource(manifests).ListAsync(Ct);
StoreGame aw = epic.Should().ContainSingle().Subject;
aw.Platform.Should().Be("epic");
aw.StoreId.Should().Be("dcbb1ebd");
aw.ExePath.Should().Be(@"D:\Epic Games\AlanWake2\AlanWake2.exe");
aw.Version.Should().Be("1.2.3");
string apps = Sub("itch", "apps");
string install = Sub("itch", "apps", "celeste");
Directory.CreateDirectory(Path.Combine(install, ".itch"));
using (FileStream f = File.Create(Path.Combine(install, ".itch", "receipt.json.gz")))
using (var gz = new GZipStream(f, CompressionLevel.Fastest))
{
byte[] json = Encoding.UTF8.GetBytes("{\"game\":{\"id\":36776,\"title\":\"Celeste\"},\"files\":[\"Celeste.exe\"]}");
await gz.WriteAsync(json, Ct);
}
Sub("itch", "apps", "empty");
IReadOnlyList<StoreGame> itch = await new ItchLibrarySource(apps).ListAsync(Ct);
StoreGame c = itch.Should().ContainSingle().Subject;
c.Platform.Should().Be("itch");
c.StoreId.Should().Be("36776");
c.Name.Should().Be("Celeste");
c.InstallDirectory.Should().Be(install);
c.ExePath.Should().BeNull();
(await new EpicLibrarySource(Path.Combine(_dir, "nowhere")).ListAsync(Ct)).Should().BeEmpty();
(await new ItchLibrarySource(Path.Combine(_dir, "nowhere")).ListAsync(Ct)).Should().BeEmpty();
}
[Fact]
public async Task TheLocatorTakesTheLargestNonHelperExecutableWithinThreeLevels()
{
string game = Sub("Game");
string bin = Sub("Game", "Binaries", "Win64");
await File.WriteAllBytesAsync(Path.Combine(game, "Launcher.exe"), new byte[10], Ct);
await File.WriteAllBytesAsync(Path.Combine(game, "UnityCrashHandler64.exe"), new byte[5000], Ct);
await File.WriteAllBytesAsync(Path.Combine(bin, "Title-Win64-Shipping.exe"), new byte[4000], Ct);
await File.WriteAllBytesAsync(Path.Combine(bin, "EasyAntiCheat_Setup.exe"), new byte[9000], Ct);
string deep = Sub("Game", "a", "b", "c", "d");
await File.WriteAllBytesAsync(Path.Combine(deep, "TooDeep.exe"), new byte[99999], Ct);
var locator = new ExecutableLocator();
locator.PickPrimary(game).Should().Be(Path.Combine(bin, "Title-Win64-Shipping.exe"), "helpers are dropped by name, the fourth level is not walked, the largest survivor wins");
locator.PickPrimary(Path.Combine(_dir, "nowhere")).Should().BeNull();
ExecutableLocator.IsHelper("vc_redist.x64").Should().BeTrue();
ExecutableLocator.IsHelper("Cyberpunk2077").Should().BeFalse();
}
}
@@ -0,0 +1,68 @@
using FluentAssertions;
using FrameLedger.Infrastructure.Import;
namespace FrameLedger.Infrastructure.Tests.Import;
/// <summary>Valve's KeyValues text (P4 PR-4): the two Steam files' shapes, comments, escapes, case-insensitive keys, and malformed input that costs an answer rather than throwing.</summary>
public sealed class ValveKeyValuesTests
{
[Fact]
public void AnAppManifestReadsBackItsFields()
{
const string acf = """
"AppState"
{
"appid" "1091500"
"name" "Cyberpunk 2077"
"installdir" "Cyberpunk 2077"
"buildid" "15877371" // a comment after the value
"UserConfig"
{
"language" "english"
}
}
""";
KeyValuesBlock root = ValveKeyValues.Parse(acf);
KeyValuesBlock state = root.Child("appstate")!;
state.Should().NotBeNull("keys compare case-insensitively");
state.Value("appid").Should().Be("1091500");
state.Value("name").Should().Be("Cyberpunk 2077");
state.Value("installdir").Should().Be("Cyberpunk 2077");
state.Value("buildid").Should().Be("15877371");
state.Child("UserConfig")!.Value("language").Should().Be("english");
}
[Fact]
public void LibraryFoldersListsEveryPathAndEscapesAreHonoured()
{
const string vdf = """
"libraryfolders"
{
"0"
{
"path" "C:\\Program Files (x86)\\Steam"
"apps" { "228980" "1234" }
}
"1"
{
"path" "D:\\SteamLibrary"
"label" "say \"hi\""
}
}
""";
KeyValuesBlock folders = ValveKeyValues.Parse(vdf).Child("libraryfolders")!;
folders.Children.Select(static c => c.Value.Value("path")).Should().Equal(@"C:\Program Files (x86)\Steam", @"D:\SteamLibrary");
folders.Child("1")!.Value("label").Should().Be("say \"hi\"");
folders.Child("0")!.Child("apps")!.Value("228980").Should().Be("1234", "bare and quoted tokens both parse");
}
[Fact]
public void MalformedInputCostsAnAnswerNotAnException()
{
ValveKeyValues.Parse("\"AppState\" { \"appid\" \"1\" ").Child("AppState")!.Value("appid").Should().Be("1", "an unterminated block keeps what parsed");
ValveKeyValues.Parse("\"key\"").Value("key").Should().BeNull("a key with no value is dropped");
ValveKeyValues.Parse("}}}{{{").Entries.Should().BeEmpty();
ValveKeyValues.Parse(string.Empty).Entries.Should().BeEmpty();
ValveKeyValues.Parse("\"unterminated").Entries.Should().BeEmpty();
}
}
@@ -88,6 +88,39 @@ public sealed class SqliteGameRepositoryTests
(await repo.ApplyDetectionAsync(row.Id + 99, new DetectionWrite { CapabilityIds = [], RulesVersion = "v", ExeSizeBytes = 0, ExeMtimeMs = 0 }, Ct)).Should().BeFalse();
}
/// <summary>The import's write (P4 PR-4) under the same provenance rule: a store fills empty fields and badges them; a user's platform stays; a null store value erases nothing; the hook columns are untouched.</summary>
[Fact]
public async Task AStoreWriteFillsAndBadgesButNeverOverwritesTheUser()
{
await using LedgerFixture f = await LedgerFixture.OpenAsync();
var repo = new SqliteGameRepository(f.Db);
GameRow row = await repo.EnsureAsync(_exe, "T", Ct);
(await repo.ApplyStoreMetadataAsync(row.Id, new StoreMetadata { Platform = "steam", StoreId = "1091500", GameVersion = "15877371" }, Ct)).Should().BeTrue();
GameRow first = (await repo.FindByIdAsync(row.Id, Ct))!;
first.Platform.Should().Be("steam");
first.StoreId.Should().Be("1091500");
first.GameVersion.Should().Be("15877371");
first.HookEnabled.Should().BeFalse("import never enables hooking");
JsonSerializer.Deserialize<Dictionary<string, string>>(first.FieldProvenanceJson!).Should().BeEquivalentTo(new Dictionary<string, string>(StringComparer.Ordinal)
{
["platform"] = "detected",
["store_id"] = "detected",
["game_version"] = "detected",
});
(await repo.UpdateMetadataAsync(row.Id, new GameMetadata { Name = "T", Platform = "gog", StoreId = "1091500", GameVersion = "15877371" }, Ct)).Should().BeTrue();
(await repo.ApplyStoreMetadataAsync(row.Id, new StoreMetadata { Platform = "epic", StoreId = "e1", GameVersion = null }, Ct)).Should().BeTrue();
GameRow second = (await repo.FindByIdAsync(row.Id, Ct))!;
second.Platform.Should().Be("gog", "the user chose it");
second.StoreId.Should().Be("e1", "still badged detected, so refreshed");
second.GameVersion.Should().Be("15877371", "null erases nothing");
Func<Task> notAStore = async () => await repo.ApplyStoreMetadataAsync(row.Id, new StoreMetadata { Platform = "none" }, Ct).ConfigureAwait(true);
await notAStore.Should().ThrowAsync<ArgumentException>();
(await repo.ApplyStoreMetadataAsync(row.Id + 99, new StoreMetadata { Platform = "steam" }, Ct)).Should().BeFalse();
}
private static async Task<long> AddSessionAsync(LedgerFixture f, long gameId)
{
long snapshotId = await new SqliteHardwareSnapshotRepository(f.Db).EnsureAsync(new HardwareSnapshot { GpuName = "G" }, DateTimeOffset.UnixEpoch, Ct).ConfigureAwait(false);