diff --git a/Directory.Build.props b/Directory.Build.props index 913c761..20cc73a 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -5,7 +5,7 @@ enable latest true - 2.0.1 + 2.0.2 $(VersionSuffix).$(RepriseBuildNumber) $(VersionPrefix)+$(RepriseBuildNumber) diff --git a/src/Reprise.Core/MediaSessionSnapshot.cs b/src/Reprise.Core/MediaSessionSnapshot.cs index d4d8d96..92786fe 100644 --- a/src/Reprise.Core/MediaSessionSnapshot.cs +++ b/src/Reprise.Core/MediaSessionSnapshot.cs @@ -52,7 +52,8 @@ public sealed record MediaSessionSnapshot( TimeSpan? Position, double? Volume, Uri? ArtworkUri, - DateTimeOffset ObservedAt) + DateTimeOffset ObservedAt, + string? CollectionEvidence = null) { /// /// Fraction of the track that has already played, as a progress-bar value. diff --git a/src/Reprise.Desktop/NowPlayingViewModel.cs b/src/Reprise.Desktop/NowPlayingViewModel.cs index 0efd7d1..258ca00 100644 --- a/src/Reprise.Desktop/NowPlayingViewModel.cs +++ b/src/Reprise.Desktop/NowPlayingViewModel.cs @@ -145,13 +145,15 @@ public NowPlayingViewModel( IArtworkLoader? artworkLoader = null, TimeProvider? timeProvider = null, ILyricsService? lyricsService = null, - Func? preferences = null) + Func? preferences = null, + RecordShopConnection? recordShop = null) { _mediaSessionService = mediaSessionService; _artworkLoader = artworkLoader ?? new ArtworkLoader(); _timeProvider = timeProvider ?? TimeProvider.System; _lyricsService = lyricsService; _preferences = preferences ?? DefaultPreferences; + RecordShop = recordShop; } /// @@ -173,6 +175,9 @@ public NowPlayingViewModel( /// public IReadOnlyList Sessions => _sessions; + /// Optional, explicitly connected public listening collector. + public RecordShopConnection? RecordShop { get; } + /// /// The session currently on display, or null when nothing is playing. /// @@ -427,6 +432,7 @@ public async Task RefreshAsync() : session).ToList(); _sessions = sessions; Apply(SelectActive(sessions, started)); + RecordShop?.Observe(sessions, ActiveSession, ArtworkData); SetPollError(null); } catch (OperationCanceledException) when (_lifetime.IsCancellationRequested) diff --git a/src/Reprise.Desktop/RecordShopConnection.cs b/src/Reprise.Desktop/RecordShopConnection.cs new file mode 100644 index 0000000..646926b --- /dev/null +++ b/src/Reprise.Desktop/RecordShopConnection.cs @@ -0,0 +1,275 @@ +using System.Diagnostics; +using System.Net; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Runtime.InteropServices; +using System.Text.Json; +using Reprise.Core; + +namespace Reprise.Desktop; + +/// Opt-in, online-only collection with account-wide coordination owned by the server. +public sealed class RecordShopConnection : IDisposable +{ + private readonly HttpClient _http; + private readonly Uri _origin; + private readonly string _secretPath; + private readonly CancellationTokenSource _lifetime = new(); + private CancellationTokenSource? _pairing; + private Credentials? _credentials; + private Sample? _sample; + private long _observedTick; + private Lease? _lease; + private object? _pending; + private Sample? _pendingSample; + private readonly HashSet _uploadedArtwork = []; + private readonly Task _loop; + + /// Loads a private installation credential; no traffic is sent until the user connects. + public RecordShopConnection(string? origin = null, string? secretPath = null, HttpMessageHandler? handler = null) + { + _origin = new Uri(origin ?? Environment.GetEnvironmentVariable("REPRISE_RECORD_SHOP_URL") ?? "https://reprise.mx"); + if (_origin.Scheme != "https" && !(_origin.Scheme == "http" && _origin.IsLoopback)) + throw new ArgumentException("Record Shop requires HTTPS or a loopback development server.", nameof(origin)); + _secretPath = secretPath ?? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Reprise", "record-shop.bin"); + _http = new HttpClient(handler ?? new HttpClientHandler { AllowAutoRedirect = false }) { BaseAddress = _origin, Timeout = TimeSpan.FromSeconds(15) }; + try + { + if (File.Exists(_secretPath)) + { + var bytes = File.ReadAllBytes(_secretPath); + if (OperatingSystem.IsWindows()) bytes = Protect(bytes, decrypt: true); + _credentials = JsonSerializer.Deserialize(bytes); + } + } + catch (Exception error) when (error is IOException or UnauthorizedAccessException or JsonException or System.ComponentModel.Win32Exception) { } + Status = _credentials is null ? "연결되지 않음" : "연결됨 · 다음 재생을 기다리는 중"; + _loop = RunAsync(); + } + + /// Human-readable network and collection status, without exposing bearer credentials. + public string Status { get; private set; } + /// The one-time code shown while the browser asks the user for consent. + public string? PairingCode { get; private set; } + /// Whether this installation has a stored credential. + public bool IsConnected => _credentials is not null; + /// Whether a browser pairing attempt is already in progress. + public bool IsConnecting => _pairing is not null; + + /// Captures the freshest real poll; local output takes priority over mirrored remote state. + public void Observe(IReadOnlyList sessions, MediaSessionSnapshot? active, byte[]? artwork) + { + var selected = sessions.FirstOrDefault(s => s.Status == PlaybackStatus.Playing && s.CollectionEvidence == "local_output") + ?? active; + if (selected is null || string.IsNullOrWhiteSpace(selected.Title) || string.IsNullOrWhiteSpace(selected.Artist)) + { + _sample = null; + } + else + { + var provider = Provider(selected.PlayerName); + _sample = new Sample(new Observation(selected.Title, selected.Artist, selected.Album, + selected.Duration is { TotalSeconds: > 0 } duration ? duration.TotalSeconds : null, + selected.Position?.TotalSeconds, selected.Status == PlaybackStatus.Playing, provider, + selected.CollectionEvidence ?? (provider == "spotify" ? "remote_state" : "app_state")), + selected.ArtworkUri, selected == active ? artwork : null); + } + _observedTick = Stopwatch.GetTimestamp(); + } + + /// Pairs through the user's browser, then stores the one-time issued installation token. + public async Task ConnectAsync(Action openBrowser) + { + if (IsConnecting || IsConnected) return; + using var pairing = CancellationTokenSource.CreateLinkedTokenSource(_lifetime.Token); + pairing.CancelAfter(TimeSpan.FromMinutes(10)); + _pairing = pairing; + try + { + using var start = await _http.PostAsJsonAsync("/api/device/start", new { name = $"Reprise · {Environment.MachineName}" }, pairing.Token); + start.EnsureSuccessStatusCode(); + var grant = await start.Content.ReadFromJsonAsync(JsonOptions, pairing.Token) ?? throw new IOException("Empty pairing response."); + var uri = new Uri(grant.VerificationUri); + if (uri.GetLeftPart(UriPartial.Authority) != _origin.GetLeftPart(UriPartial.Authority) || uri.AbsolutePath != "/connect") + throw new IOException("Unexpected verification URL."); + PairingCode = grant.UserCode; + Status = $"브라우저에서 Google 로그인 후 코드 {grant.UserCode}를 확인하세요."; + openBrowser(uri); + while (!pairing.IsCancellationRequested) + { + await Task.Delay(TimeSpan.FromSeconds(Math.Clamp(grant.Interval, 5, 30)), pairing.Token); + using var poll = await _http.PostAsJsonAsync("/api/device/token", new { device_code = grant.DeviceCode }, pairing.Token); + if (poll.StatusCode is HttpStatusCode.Accepted or HttpStatusCode.TooManyRequests) continue; + poll.EnsureSuccessStatusCode(); + var result = await poll.Content.ReadFromJsonAsync(JsonOptions, pairing.Token) ?? throw new IOException("Empty token response."); + var credentials = new Credentials(result.AccessToken, result.DeviceId); + Save(credentials); + _credentials = credentials; + _lease = null; + _pending = null; + Status = "연결됨 · 재생 기록 전송에 동의했습니다."; + return; + } + } + catch (OperationCanceledException) { Status = "연결이 취소되었거나 만료되었습니다."; } + catch (Exception error) when (error is HttpRequestException or IOException or JsonException or System.ComponentModel.Win32Exception) + { Status = "연결하지 못했습니다. 서버 주소와 Google 로그인 설정을 확인하세요."; } + finally { PairingCode = null; _pairing = null; } + } + + /// Cancels the pending browser pairing without changing an existing credential. + public void CancelConnect() => _pairing?.Cancel(); + + /// Stops local transmission immediately and attempts server-side installation revocation. + public async Task DisconnectAsync() + { + _pairing?.Cancel(); + var credentials = _credentials; + _credentials = null; _lease = null; _pending = null; _sample = null; + if (File.Exists(_secretPath)) File.Delete(_secretPath); + Status = "연결 해제됨"; + if (credentials is null) return; + try + { + using var request = Authenticated(HttpMethod.Delete, $"/api/devices/{credentials.DeviceId}", credentials); + using var response = await _http.SendAsync(request, _lifetime.Token); + if (!response.IsSuccessStatusCode && response.StatusCode != HttpStatusCode.Unauthorized) + Status = "로컬 연결 해제됨 · 웹 프로필에서 서버 연결도 해제해 주세요."; + } + catch (Exception error) when (error is HttpRequestException or OperationCanceledException) + { Status = "로컬 연결 해제됨 · 웹 프로필에서 서버 연결도 해제해 주세요."; } + } + + /// Reports online observations at ten-second intervals; offline history is never backfilled. + private async Task RunAsync() + { + while (!_lifetime.IsCancellationRequested) + { + try + { + await Task.Delay(TimeSpan.FromSeconds(10), _lifetime.Token); + if (_credentials is { } credentials) await SendAsync(credentials, _lifetime.Token); + } + catch (OperationCanceledException) when (_lifetime.IsCancellationRequested) { break; } + catch (Exception error) when (error is HttpRequestException or IOException or JsonException or OperationCanceledException) + { Status = "연결 재시도 중 · 확인되지 않은 구간은 집계하지 않습니다."; } + } + } + + /// Retries the exact pending sequence after transport failure and uploads real artwork after credit. + private async Task SendAsync(Credentials credentials, CancellationToken cancellationToken) + { + var sample = Stopwatch.GetElapsedTime(_observedTick) < TimeSpan.FromSeconds(5) ? _sample : null; + if (_pending is null) + { + _pendingSample = sample; + _pending = new { epoch = _lease?.Epoch, nonce = _lease?.Nonce, sequence = _lease?.NextSequence, observation = sample?.Observation }; + } + using var request = Authenticated(HttpMethod.Post, "/api/collector", credentials); + request.Content = JsonContent.Create(_pending, options: JsonOptions); + using var response = await _http.SendAsync(request, cancellationToken); + if (_credentials != credentials) return; + if (response.StatusCode == HttpStatusCode.Unauthorized) + { + _credentials = null; _lease = null; _pending = null; + if (File.Exists(_secretPath)) File.Delete(_secretPath); + Status = "서버에서 연결이 해제되었습니다."; return; + } + if (response.StatusCode is HttpStatusCode.Conflict or HttpStatusCode.TooManyRequests) + { _lease = null; _pending = null; return; } + response.EnsureSuccessStatusCode(); + var result = await response.Content.ReadFromJsonAsync(JsonOptions, cancellationToken) ?? throw new IOException("Empty collector response."); + _pending = null; + _lease = result.Role == "owner" ? result : null; + Status = result.Role == "observer" ? "연결됨 · 다른 기기에서 집계 중" : result.CreditedSeconds > 0 + ? "연결됨 · 서버에서 청취 시간 집계 중" : "연결됨 · 재생 상태 확인 중"; + if (result.CreditedSeconds <= 0 || result.TrackId is not { } trackId || sample is null || _uploadedArtwork.Contains(trackId)) return; + sample = _pendingSample; + if (sample is null) return; + var artwork = sample.Artwork; + if (artwork is null && sample.ArtworkUri is { } uri) artwork = await new ArtworkLoader().LoadAsync(uri, cancellationToken); + if (artwork is not { Length: > 0 and <= 2097152 }) return; + using var upload = Authenticated(HttpMethod.Put, $"/api/artwork/{trackId}", credentials); + upload.Content = new ByteArrayContent(artwork); + using var uploaded = await _http.SendAsync(upload, cancellationToken); + if (uploaded.IsSuccessStatusCode) _uploadedArtwork.Add(trackId); + } + + /// Attaches a bearer credential only to a request for the configured service origin. + private static HttpRequestMessage Authenticated(HttpMethod method, string path, Credentials credentials) + { + var request = new HttpRequestMessage(method, path); + request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", credentials.Token); + return request; + } + + /// Writes a private credential file, protected with DPAPI on Windows. + private void Save(Credentials credentials) + { + var directory = Path.GetDirectoryName(_secretPath)!; + Directory.CreateDirectory(directory); + var bytes = JsonSerializer.SerializeToUtf8Bytes(credentials); + if (OperatingSystem.IsWindows()) bytes = Protect(bytes, decrypt: false); + var temporary = _secretPath + ".tmp"; + var options = new FileStreamOptions { Mode = FileMode.Create, Access = FileAccess.Write, Share = FileShare.None }; + if (!OperatingSystem.IsWindows()) options.UnixCreateMode = UnixFileMode.UserRead | UnixFileMode.UserWrite; + using (var file = new FileStream(temporary, options)) file.Write(bytes); + File.Move(temporary, _secretPath, overwrite: true); + } + + /// Encrypts or decrypts a current-user DPAPI blob without UI prompts or shared secrets. + private static byte[] Protect(byte[] bytes, bool decrypt) + { + var input = new Blob { Length = bytes.Length, Data = Marshal.AllocHGlobal(bytes.Length) }; + try + { + Marshal.Copy(bytes, 0, input.Data, bytes.Length); + var success = decrypt ? CryptUnprotectData(ref input, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, 1, out var output) + : CryptProtectData(ref input, null, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, 1, out output); + if (!success) throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error()); + try { var result = new byte[output.Length]; Marshal.Copy(output.Data, result, 0, output.Length); return result; } + finally { LocalFree(output.Data); } + } + finally { Marshal.FreeHGlobal(input.Data); } + } + + /// Maps player identities to stable collection providers. + internal static string Provider(string name) => name.ToLowerInvariant() switch + { + var value when value.Contains("spotify") => "spotify", + var value when value.Contains("melon") || value.Contains("멜론") => "melon", + var value when value.Contains("youtube") => "youtube-music", + var value when value.Contains("apple") || value == "music" => "apple-music", + _ => "other", + }; + + /// Stops timers and cancels all requests without changing server playback. + public void Dispose() { _pairing?.Cancel(); _lifetime.Cancel(); _http.Dispose(); } + + /// JSON field naming shared with the Worker device protocol. + private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web) { PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower, DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull }; + /// Only this installation's opaque credential is persisted. + private sealed record Credentials(string Token, string DeviceId); + /// Short-lived browser pairing values. + private sealed record Grant(string DeviceCode, string UserCode, string VerificationUri, int Interval); + /// A one-time credential returned after browser consent. + private sealed record TokenResult(string AccessToken, string DeviceId); + /// Server-owned lease values; clients never supply a credited time. + private sealed record Lease(string Role, string? Epoch, string? Nonce, long? NextSequence, double CreditedSeconds, string? TrackId); + /// Metadata and state measured from the existing platform backend. + private sealed record Observation(string Title, string Artist, string Album, double? DurationSeconds, double? PositionSeconds, bool Playing, string Provider, string Evidence); + /// Transient artwork stays local until a real interval has been accepted. + private sealed record Sample(Observation Observation, Uri? ArtworkUri, byte[]? Artwork); + /// Native DATA_BLOB used by the current-user Windows credential protector. + [StructLayout(LayoutKind.Sequential)] private struct Blob { public int Length; public IntPtr Data; } + /// Protects bytes with the current Windows user's key. + [DllImport("crypt32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool CryptProtectData(ref Blob data, string? description, IntPtr entropy, IntPtr reserved, IntPtr prompt, int flags, out Blob output); + /// Unprotects bytes only for the Windows user who stored them. + [DllImport("crypt32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool CryptUnprotectData(ref Blob data, IntPtr description, IntPtr entropy, IntPtr reserved, IntPtr prompt, int flags, out Blob output); + /// Releases a buffer returned by DPAPI. + [DllImport("kernel32.dll")] private static extern IntPtr LocalFree(IntPtr memory); +} diff --git a/src/Reprise.Desktop/RepriseApplication.cs b/src/Reprise.Desktop/RepriseApplication.cs index 755be43..54b4feb 100644 --- a/src/Reprise.Desktop/RepriseApplication.cs +++ b/src/Reprise.Desktop/RepriseApplication.cs @@ -153,10 +153,13 @@ public override void OnFrameworkInitializationCompleted() ? new AutomaticApplicationUpdater(platformUpdater, preferences) : null; updater?.Start(); desktop.Exit += (_, _) => updater?.Dispose(); + var recordShop = new RecordShopConnection(); + desktop.Exit += (_, _) => recordShop.Dispose(); var viewModel = new NowPlayingViewModel( service, lyricsService: new LyricsService(), - preferences: () => preferences.Current); + preferences: () => preferences.Current, + recordShop: recordShop); viewModel.LastPlayedPlayerChanged += (_, kind) => Dispatcher.UIThread.Post(() => preferences.Update(p => p with { LastPlayedPlayer = kind.ToString() })); var window = new NowPlayingWindow(viewModel, preferences); diff --git a/src/Reprise.Desktop/SettingsWindow.cs b/src/Reprise.Desktop/SettingsWindow.cs index 5bd4041..e53039e 100644 --- a/src/Reprise.Desktop/SettingsWindow.cs +++ b/src/Reprise.Desktop/SettingsWindow.cs @@ -41,6 +41,9 @@ public sealed class SettingsWindow : Window private StackPanel? _priorityList; private TextBlock? _autostartError; private ToggleSwitch? _autostartToggle; + private TextBlock? _recordShopStatus; + private Button? _recordShopConnect; + private Button? _recordShopDisconnect; /// /// Whether the application is shutting down and the window may close. @@ -119,7 +122,7 @@ public SettingsWindow( _sessionTimer = new DispatcherTimer( TimeSpan.FromMilliseconds(500), DispatcherPriority.Background, - (_, _) => RefreshSessions()); + (_, _) => { RefreshSessions(); RefreshRecordShop(); }); _preferences.Changed += (_, _) => RefreshAll(); Opened += (_, _) => @@ -335,7 +338,45 @@ private Control BuildGeneralTab() "로그인하면 Reprise를 자동으로 실행합니다.", autostartRow, _autostartError); - return SettingsForm.Page(playback, lyricsSection, priority, startup); + return _viewModel.RecordShop is null + ? SettingsForm.Page(playback, lyricsSection, priority, startup) + : SettingsForm.Page(playback, lyricsSection, priority, startup, BuildRecordShopSection()); + } + + /// Offers explicit browser consent before sending any playback metadata. + private Control BuildRecordShopSection() + { + var connection = _viewModel.RecordShop!; + _recordShopStatus = new TextBlock { Text = connection.Status, TextWrapping = TextWrapping.Wrap, Margin = new Thickness(14, 10), FontSize = PanelTypography.Subtitle }; + _recordShopConnect = new Button { Content = "Google 계정 연결" }; + _recordShopDisconnect = new Button { Content = "연결 해제" }; + _recordShopConnect.Click += async (_, _) => + { + var task = connection.ConnectAsync(uri => System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(uri.AbsoluteUri) { UseShellExecute = true })); + RefreshRecordShop(); + await task; + RefreshRecordShop(); + }; + _recordShopDisconnect.Click += async (_, _) => + { + if (connection.IsConnecting) connection.CancelConnect(); + else await connection.DisconnectAsync(); + RefreshRecordShop(); + }; + var actions = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8, Children = { _recordShopConnect, _recordShopDisconnect } }; + RefreshRecordShop(); + return SettingsForm.Section("Reprise.mx", "연결 후 곡명·아티스트·앨범·재생 상태를 전송하며, 프로필과 청취 시간이 공개 차트에 표시됩니다.", + SettingsForm.Row("청취 기록 공유", actions), _recordShopStatus); + } + + /// Reflects asynchronous pairing and revocation in the existing settings timer. + private void RefreshRecordShop() + { + if (_viewModel.RecordShop is not { } connection || _recordShopStatus is null) return; + _recordShopStatus.Text = connection.Status; + _recordShopConnect!.IsEnabled = !connection.IsConnected && !connection.IsConnecting; + _recordShopDisconnect!.IsEnabled = connection.IsConnected || connection.IsConnecting; + _recordShopDisconnect.Content = connection.IsConnecting ? "연결 취소" : "연결 해제"; } /// diff --git a/src/Reprise.Platform.MacOS/Reprise.xcodeproj/project.pbxproj b/src/Reprise.Platform.MacOS/Reprise.xcodeproj/project.pbxproj index b79d5ec..09eb9e9 100644 --- a/src/Reprise.Platform.MacOS/Reprise.xcodeproj/project.pbxproj +++ b/src/Reprise.Platform.MacOS/Reprise.xcodeproj/project.pbxproj @@ -420,7 +420,7 @@ ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; CODE_SIGN_ENTITLEMENTS = Reprise/Reprise.entitlements; CODE_SIGN_STYLE = Automatic; - CURRENT_PROJECT_VERSION = 5; + CURRENT_PROJECT_VERSION = 6; DEVELOPMENT_TEAM = 85VUD9PZRQ; ENABLE_APP_SANDBOX = YES; ENABLE_HARDENED_RUNTIME = YES; @@ -442,7 +442,7 @@ LD_RUNPATH_SEARCH_PATHS = "@executable_path/Frameworks"; "LD_RUNPATH_SEARCH_PATHS[sdk=macosx*]" = "@executable_path/../Frameworks"; MACOSX_DEPLOYMENT_TARGET = 14.0; - MARKETING_VERSION = 2.0.1; + MARKETING_VERSION = 2.0.2; PRODUCT_BUNDLE_IDENTIFIER = dev.junx.Reprise; PRODUCT_NAME = "$(TARGET_NAME)"; REGISTER_APP_GROUPS = YES; @@ -466,7 +466,7 @@ ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; CODE_SIGN_ENTITLEMENTS = Reprise/Reprise.entitlements; CODE_SIGN_STYLE = Automatic; - CURRENT_PROJECT_VERSION = 5; + CURRENT_PROJECT_VERSION = 6; DEVELOPMENT_TEAM = 85VUD9PZRQ; ENABLE_APP_SANDBOX = YES; ENABLE_HARDENED_RUNTIME = YES; @@ -488,7 +488,7 @@ LD_RUNPATH_SEARCH_PATHS = "@executable_path/Frameworks"; "LD_RUNPATH_SEARCH_PATHS[sdk=macosx*]" = "@executable_path/../Frameworks"; MACOSX_DEPLOYMENT_TARGET = 14.0; - MARKETING_VERSION = 2.0.1; + MARKETING_VERSION = 2.0.2; PRODUCT_BUNDLE_IDENTIFIER = dev.junx.Reprise; PRODUCT_NAME = "$(TARGET_NAME)"; REGISTER_APP_GROUPS = YES; @@ -510,12 +510,12 @@ buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; CODE_SIGN_STYLE = Automatic; - CURRENT_PROJECT_VERSION = 5; + CURRENT_PROJECT_VERSION = 6; DEVELOPMENT_TEAM = 85VUD9PZRQ; GENERATE_INFOPLIST_FILE = YES; IPHONEOS_DEPLOYMENT_TARGET = 26.5; MACOSX_DEPLOYMENT_TARGET = 14.0; - MARKETING_VERSION = 2.0.1; + MARKETING_VERSION = 2.0.2; PRODUCT_BUNDLE_IDENTIFIER = dev.junx.RepriseTests; PRODUCT_NAME = "$(TARGET_NAME)"; SDKROOT = macosx; @@ -536,12 +536,12 @@ buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; CODE_SIGN_STYLE = Automatic; - CURRENT_PROJECT_VERSION = 5; + CURRENT_PROJECT_VERSION = 6; DEVELOPMENT_TEAM = 85VUD9PZRQ; GENERATE_INFOPLIST_FILE = YES; IPHONEOS_DEPLOYMENT_TARGET = 26.5; MACOSX_DEPLOYMENT_TARGET = 14.0; - MARKETING_VERSION = 2.0.1; + MARKETING_VERSION = 2.0.2; PRODUCT_BUNDLE_IDENTIFIER = dev.junx.RepriseTests; PRODUCT_NAME = "$(TARGET_NAME)"; SDKROOT = macosx; @@ -561,12 +561,12 @@ isa = XCBuildConfiguration; buildSettings = { CODE_SIGN_STYLE = Automatic; - CURRENT_PROJECT_VERSION = 5; + CURRENT_PROJECT_VERSION = 6; DEVELOPMENT_TEAM = 85VUD9PZRQ; GENERATE_INFOPLIST_FILE = YES; IPHONEOS_DEPLOYMENT_TARGET = 26.5; MACOSX_DEPLOYMENT_TARGET = 14.0; - MARKETING_VERSION = 2.0.1; + MARKETING_VERSION = 2.0.2; PRODUCT_BUNDLE_IDENTIFIER = dev.junx.RepriseUITests; PRODUCT_NAME = "$(TARGET_NAME)"; SDKROOT = macosx; @@ -586,12 +586,12 @@ isa = XCBuildConfiguration; buildSettings = { CODE_SIGN_STYLE = Automatic; - CURRENT_PROJECT_VERSION = 5; + CURRENT_PROJECT_VERSION = 6; DEVELOPMENT_TEAM = 85VUD9PZRQ; GENERATE_INFOPLIST_FILE = YES; IPHONEOS_DEPLOYMENT_TARGET = 26.5; MACOSX_DEPLOYMENT_TARGET = 14.0; - MARKETING_VERSION = 2.0.1; + MARKETING_VERSION = 2.0.2; PRODUCT_BUNDLE_IDENTIFIER = dev.junx.RepriseUITests; PRODUCT_NAME = "$(TARGET_NAME)"; SDKROOT = macosx; diff --git a/src/Reprise.Platform.MacOS/Reprise/NowPlayingStore.swift b/src/Reprise.Platform.MacOS/Reprise/NowPlayingStore.swift index d5fb0a7..bbffdc8 100644 --- a/src/Reprise.Platform.MacOS/Reprise/NowPlayingStore.swift +++ b/src/Reprise.Platform.MacOS/Reprise/NowPlayingStore.swift @@ -333,6 +333,7 @@ final class NowPlayingStore { currentSnapshots: snapshotsByPlayer ) synchronizeLyricsWithActiveTrack(observedAt: Date()) + RecordShopConnection.shared.observe(menuBarSnapshot) if MediaPlayerKind.allCases.contains(where: { player in Self.menuBarContentChanged( from: previousSnapshots[player] diff --git a/src/Reprise.Platform.MacOS/Reprise/RecordShopConnection.swift b/src/Reprise.Platform.MacOS/Reprise/RecordShopConnection.swift new file mode 100644 index 0000000..c4c2d69 --- /dev/null +++ b/src/Reprise.Platform.MacOS/Reprise/RecordShopConnection.swift @@ -0,0 +1,238 @@ +import AppKit +import Foundation +import Observation +import Security +import SwiftUI + +/// An opt-in collector. Google identity and interval accounting are owned by the server. +@MainActor @Observable +final class RecordShopConnection { + /// One connection shared by the real player store and settings window. + static let shared = RecordShopConnection() + private(set) var status = "연결되지 않음" + private(set) var pairingCode: String? + private(set) var isConnecting = false + private(set) var isConnected = false + private let origin: URL + private let session: URLSession + private var credentials: Credentials? + private var pairingTask: Task? + private var collectionTask: Task? + private var observation: [String: Any]? + private var artwork: Data? + private var observedAt: TimeInterval = 0 + private var lease: Lease? + private var pending: Data? + private var pendingArtwork: Data? + private var uploaded: Set = [] + + /// Restores a Keychain credential; no listening information is sent before pairing. + private init() { + let configured = ProcessInfo.processInfo.environment["REPRISE_RECORD_SHOP_URL"] ?? "https://reprise.mx" + let candidate = URL(string: configured) + let isLoopback = ["localhost", "127.0.0.1", "::1"].contains(candidate?.host ?? "") + origin = candidate?.scheme == "https" || (candidate?.scheme == "http" && isLoopback) + ? candidate! : URL(string: "https://reprise.mx")! + let config = URLSessionConfiguration.ephemeral + config.timeoutIntervalForRequest = 15 + session = URLSession(configuration: config) + if let data = Self.readSecret(service: origin.absoluteString), let value = try? JSONDecoder().decode(Credentials.self, from: data) { + credentials = value + isConnected = true + status = "연결됨 · 다음 재생을 기다리는 중" + } + } + + /// Records only the real polling path; demo snapshots never call this method. + func observe(_ snapshot: PlayerSnapshot?) { + defer { observedAt = ProcessInfo.processInfo.systemUptime; startCollection() } + guard let snapshot, let track = snapshot.track, !track.title.isEmpty, !track.artist.isEmpty else { + observation = nil; artwork = nil; return + } + let provider: String + switch snapshot.player { + case .spotify: provider = "spotify" + case .appleMusic: provider = "apple-music" + case .youtubeMusic: provider = "youtube-music" + } + observation = ["title": track.title, "artist": track.artist, "album": track.album, + "playing": snapshot.state.isPlaying, "provider": provider, + "evidence": provider == "spotify" ? "remote_state" : "app_state"] + if track.duration.isFinite && track.duration > 0 { observation?["duration_seconds"] = track.duration } + if track.position.isFinite && track.position >= 0 { observation?["position_seconds"] = track.position } + artwork = track.artworkData + } + + /// Opens a browser for Google sign-in and explicit public-chart consent. + func connect() { + guard !isConnecting, !isConnected else { return } + isConnecting = true + pairingTask = Task { [weak self] in + guard let self else { return } + defer { isConnecting = false; pairingCode = nil; pairingTask = nil } + do { + let grant: Grant = try await request("/api/device/start", body: ["name": "Reprise · \(Host.current().localizedName ?? "Mac")"]) + guard let url = URL(string: grant.verificationUri), url.host == origin.host, + url.port == origin.port, url.scheme == origin.scheme, url.path == "/connect" else { throw ConnectionError.invalidResponse } + pairingCode = grant.userCode + status = "브라우저에서 Google 로그인 후 코드 \(grant.userCode)를 확인하세요." + NSWorkspace.shared.open(url) + let expires = ProcessInfo.processInfo.systemUptime + 600 + while ProcessInfo.processInfo.systemUptime < expires { + try await Task.sleep(for: .seconds(max(5, min(30, grant.interval)))) + do { + let token: Token = try await request("/api/device/token", body: ["device_code": grant.deviceCode]) + let saved = Credentials(token: token.accessToken, deviceId: token.deviceId) + try Self.writeSecret(try JSONEncoder().encode(saved), service: origin.absoluteString) + credentials = saved; isConnected = true; lease = nil; pending = nil + status = "연결됨 · 재생 기록 전송에 동의했습니다." + startCollection() + return + } catch ConnectionError.http(202) { continue } + catch ConnectionError.http(429) { continue } + } + status = "연결 코드가 만료되었습니다. 다시 연결해 주세요." + } catch is CancellationError { status = "연결이 취소되었습니다." } + catch { status = "연결하지 못했습니다. 서버와 Google 로그인 설정을 확인하세요." } + } + } + + /// Cancels only the current pairing attempt. + func cancel() { pairingTask?.cancel() } + + /// Stops local reporting immediately, then revokes this installation on the server. + func disconnect() async { + pairingTask?.cancel() + let previous = credentials + credentials = nil; isConnected = false; lease = nil; pending = nil + collectionTask?.cancel(); collectionTask = nil + Self.deleteSecret(service: origin.absoluteString) + status = "연결 해제됨" + guard let previous else { return } + do { + var request = URLRequest(url: URL(string: "/api/devices/\(previous.deviceId)", relativeTo: origin)!) + request.httpMethod = "DELETE" + request.setValue("Bearer \(previous.token)", forHTTPHeaderField: "Authorization") + let (_, response) = try await session.data(for: request) + if let response = response as? HTTPURLResponse, ![204,401].contains(response.statusCode) { throw ConnectionError.http(response.statusCode) } + } catch { status = "로컬 연결 해제됨 · 웹 프로필에서 서버 연결도 해제해 주세요." } + } + + /// Runs one ten-second reporting loop, independently of the popover's visibility. + private func startCollection() { + guard isConnected, collectionTask == nil else { return } + collectionTask = Task { [weak self] in + while !Task.isCancelled { + do { + try await Task.sleep(for: .seconds(10)) + try await self?.send() + } catch is CancellationError { break } + catch { self?.status = "연결 재시도 중 · 확인되지 않은 구간은 집계하지 않습니다." } + } + } + } + + /// Retries identical pending requests; it never uploads a client-computed listening duration. + private func send() async throws { + guard let credentials else { return } + if pending == nil { + var body: [String: Any] = ["observation": ProcessInfo.processInfo.systemUptime - observedAt < 5 ? observation as Any? ?? NSNull() : NSNull()] + if let lease { body["epoch"] = lease.epoch; body["nonce"] = lease.nonce; body["sequence"] = lease.nextSequence } + pending = try JSONSerialization.data(withJSONObject: body) + pendingArtwork = artwork + } + var request = URLRequest(url: URL(string: "/api/collector", relativeTo: origin)!) + request.httpMethod = "POST"; request.httpBody = pending + request.setValue("application/json", forHTTPHeaderField: "Content-Type") + request.setValue("Bearer \(credentials.token)", forHTTPHeaderField: "Authorization") + let (data, rawResponse) = try await session.data(for: request) + guard self.credentials?.token == credentials.token else { return } + guard let response = rawResponse as? HTTPURLResponse else { throw ConnectionError.invalidResponse } + if response.statusCode == 401 { + self.credentials = nil; isConnected = false; lease = nil; pending = nil + Self.deleteSecret(service: origin.absoluteString) + status = "서버에서 연결이 해제되었습니다." + return + } + if [409,429].contains(response.statusCode) { lease = nil; pending = nil; return } + guard [200,202].contains(response.statusCode) else { throw ConnectionError.http(response.statusCode) } + let result = try Self.decoder.decode(Lease.self, from: data) + pending = nil; lease = result.role == "owner" ? result : nil + status = result.role == "observer" ? "연결됨 · 다른 기기에서 집계 중" + : (result.creditedSeconds ?? 0) > 0 ? "연결됨 · 서버에서 청취 시간 집계 중" : "연결됨 · 재생 상태 확인 중" + guard (result.creditedSeconds ?? 0) > 0, let trackId = result.trackId, !uploaded.contains(trackId), + let artwork = pendingArtwork, artwork.count <= 2 * 1024 * 1024 else { return } + var upload = URLRequest(url: URL(string: "/api/artwork/\(trackId)", relativeTo: origin)!) + upload.httpMethod = "PUT"; upload.httpBody = artwork + upload.setValue("Bearer \(credentials.token)", forHTTPHeaderField: "Authorization") + let (_, uploadedResponse) = try await session.data(for: upload) + if (uploadedResponse as? HTTPURLResponse)?.statusCode == 200 { uploaded.insert(trackId) } + } + + /// Sends a bounded JSON request and refuses pending status as a completed authorization. + private func request(_ path: String, body: [String: Any]) async throws -> T { + var request = URLRequest(url: URL(string: path, relativeTo: origin)!) + request.httpMethod = "POST"; request.httpBody = try JSONSerialization.data(withJSONObject: body) + request.setValue("application/json", forHTTPHeaderField: "Content-Type") + let (data, response) = try await session.data(for: request) + guard let response = response as? HTTPURLResponse, response.statusCode == 200 else { + throw ConnectionError.http((response as? HTTPURLResponse)?.statusCode ?? 503) + } + return try Self.decoder.decode(T.self, from: data) + } + + /// Reads only this service's generic-password entry from the current user's Keychain. + private static func readSecret(service: String) -> Data? { + let query: [String: Any] = [kSecClass as String:kSecClassGenericPassword,kSecAttrService as String:"dev.junx.Reprise.record-shop",kSecAttrAccount as String:service,kSecReturnData as String:true] + var result: CFTypeRef? + return SecItemCopyMatching(query as CFDictionary,&result) == errSecSuccess ? result as? Data : nil + } + + /// Stores bearer credentials in Keychain, never in UserDefaults or logs. + private static func writeSecret(_ data: Data, service: String) throws { + deleteSecret(service: service) + let query: [String: Any] = [kSecClass as String:kSecClassGenericPassword,kSecAttrService as String:"dev.junx.Reprise.record-shop",kSecAttrAccount as String:service,kSecValueData as String:data,kSecAttrAccessible as String:kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly] + guard SecItemAdd(query as CFDictionary,nil) == errSecSuccess else { throw ConnectionError.keychain } + } + + /// Removes the installation credential when the user disconnects or the server revokes it. + private static func deleteSecret(service: String) { + SecItemDelete([kSecClass as String:kSecClassGenericPassword,kSecAttrService as String:"dev.junx.Reprise.record-shop",kSecAttrAccount as String:service] as CFDictionary) + } + + /// Decodes the Worker's snake-case protocol names. + private static var decoder: JSONDecoder { let value = JSONDecoder(); value.keyDecodingStrategy = .convertFromSnakeCase; return value } + /// Opaque installation credential stored only in Keychain. + private struct Credentials: Codable { let token: String; let deviceId: String } + /// Expiring browser authorization challenge. + private struct Grant: Decodable { let deviceCode: String; let userCode: String; let verificationUri: String; let interval: Int } + /// One-time token exchange result. + private struct Token: Decodable { let accessToken: String; let deviceId: String } + /// Server-owned sequence and nonce, excluding any client-side duration calculation. + private struct Lease: Decodable { let role: String; let epoch: String?; let nonce: String?; let nextSequence: Int?; let creditedSeconds: Double?; let trackId: String? } + /// Expected transport and local credential-store failures. + private enum ConnectionError: Error { case http(Int), invalidResponse, keychain } +} + +/// Explicit opt-in controls embedded in the existing General settings form. +struct RecordShopSettingsSection: View { + private var connection: RecordShopConnection { .shared } + /// Shares metadata only after browser sign-in and consent, and offers immediate disconnection. + var body: some View { + Section { + HStack { + Text("청취 기록 공유") + Spacer() + if connection.isConnected { + Button("연결 해제") { Task { await connection.disconnect() } } + } else if connection.isConnecting { + Button("연결 취소") { connection.cancel() } + } else { + Button("Google 계정 연결") { connection.connect() } + } + } + Text(connection.status).font(.caption).foregroundStyle(.secondary).textSelection(.enabled) + } header: { Text("Reprise.mx") } + footer: { Text("연결 후 곡명·아티스트·앨범·재생 상태를 전송하며, 프로필과 청취 시간이 공개 차트에 표시됩니다.") } + } +} diff --git a/src/Reprise.Platform.MacOS/Reprise/RepriseSettingsView.swift b/src/Reprise.Platform.MacOS/Reprise/RepriseSettingsView.swift index 06c9604..951afb7 100644 --- a/src/Reprise.Platform.MacOS/Reprise/RepriseSettingsView.swift +++ b/src/Reprise.Platform.MacOS/Reprise/RepriseSettingsView.swift @@ -111,6 +111,7 @@ private struct GeneralSettingsView: View { /// changed. var body: some View { Form { + RecordShopSettingsSection() Section { Toggle( "다른 플레이어 자동 정지", diff --git a/src/Reprise.Platform.Windows/Media/WindowsApplicationVolume.cs b/src/Reprise.Platform.Windows/Media/WindowsApplicationVolume.cs index 54f9578..06a9400 100644 --- a/src/Reprise.Platform.Windows/Media/WindowsApplicationVolume.cs +++ b/src/Reprise.Platform.Windows/Media/WindowsApplicationVolume.cs @@ -8,6 +8,26 @@ namespace Reprise.Platform.Windows.Media; /// Controls dedicated players through their Core Audio process sessions without touching endpoint master volume. internal static class WindowsApplicationVolume { + private static readonly System.Collections.Concurrent.ConcurrentDictionary LastOutput = new(); + + /// Observes a signed player's active output across all devices, allowing short musical silences. + internal static bool HasLocalOutput(string appId) + { + var found = false; + Visit(appId, (session, process) => + { + if (session.State != NAudio.CoreAudioApi.Interfaces.AudioSessionState.AudioSessionStateActive) return; + var path = process.MainModule?.FileName; + if (path is null || !WindowsPlayerTrust.IsTrusted(path, appId)) return; + try + { + if (session.AudioMeterInformation.MasterPeakValue > 0.00001f) LastOutput[process.Id] = Stopwatch.GetTimestamp(); + if (LastOutput.TryGetValue(process.Id, out var last) && Stopwatch.GetElapsedTime(last) < TimeSpan.FromSeconds(8)) found = true; + } + catch (NotSupportedException) { } + }); + return found; + } /// Maps known dedicated media identities to executable names; browser tabs cannot safely have independent mixer volumes. internal static bool MatchesProcess(string appId, string processName) { @@ -23,7 +43,7 @@ internal static bool MatchesProcess(string appId, string processName) internal static double? Read(string appId) { double? result = null; - Visit(appId, session => + Visit(appId, (session, _) => { var volume = session.SimpleAudioVolume; var level = volume.Mute ? 0d : volume.Volume; @@ -33,14 +53,14 @@ internal static bool MatchesProcess(string appId, string processName) } /// Sets all matching streams, including an application's dedicated output device, and unmutes when raising the level. - internal static bool Set(string appId, double value) => Visit(appId, session => + internal static bool Set(string appId, double value) => Visit(appId, (session, _) => { session.SimpleAudioVolume.Volume = (float)value; if (value > 0) session.SimpleAudioVolume.Mute = false; }); /// Reacquires sessions on an MTA worker for every operation and releases each native wrapper before returning. - private static bool Visit(string appId, Action action) + private static bool Visit(string appId, Action action) { if (!MatchesProcess(appId, "Spotify") && !MatchesProcess(appId, "Melon Player")) return false; var found = false; @@ -63,7 +83,7 @@ private static bool Visit(string appId, Action action) if (session.IsSystemSoundsSession || session.GetProcessID == 0) continue; using var process = Process.GetProcessById((int)session.GetProcessID); if (!MatchesProcess(appId, process.ProcessName)) continue; - action(session); + action(session, process); found = true; } catch (Exception error) when (error is COMException or Win32Exception or ArgumentException or InvalidOperationException) { } diff --git a/src/Reprise.Platform.Windows/Media/WindowsMediaSessionSource.cs b/src/Reprise.Platform.Windows/Media/WindowsMediaSessionSource.cs index 1a1fb48..f54202e 100644 --- a/src/Reprise.Platform.Windows/Media/WindowsMediaSessionSource.cs +++ b/src/Reprise.Platform.Windows/Media/WindowsMediaSessionSource.cs @@ -114,9 +114,12 @@ public async Task ReadAsync(CancellationToken cancellation _artworkKey = _artwork is null ? null : artworkKey; } + var localOutput = status == PlaybackStatus.Playing && await Task.Run( + () => WindowsApplicationVolume.HasLocalOutput(_session.SourceAppUserModelId), cancellationToken); return new MediaSessionSnapshot(Id, WindowsPlayerNames.DisplayName(_session.SourceAppUserModelId), status, properties.Title ?? string.Empty, properties.Artist ?? string.Empty, properties.AlbumTitle ?? string.Empty, - duration, position, await Task.Run(ReadVolume, cancellationToken), _artwork, now); + duration, position, await Task.Run(ReadVolume, cancellationToken), _artwork, now, + localOutput ? "local_output" : null); } /// diff --git a/src/Reprise.Platform.Windows/Media/WindowsPlayerTrust.cs b/src/Reprise.Platform.Windows/Media/WindowsPlayerTrust.cs new file mode 100644 index 0000000..2a01e93 --- /dev/null +++ b/src/Reprise.Platform.Windows/Media/WindowsPlayerTrust.cs @@ -0,0 +1,85 @@ +using System.Collections.Concurrent; +using System.Runtime.InteropServices; +using System.Text; + +namespace Reprise.Platform.Windows.Media; + +/// Checks executable signatures as a local signal; this is not remote client attestation. +internal static class WindowsPlayerTrust +{ + private static readonly ConcurrentDictionary Cache = new(StringComparer.OrdinalIgnoreCase); + + /// Requires a valid Authenticode signature from the expected player publisher. + internal static bool IsTrusted(string path, string appId) + { + try + { + var stamp = File.GetLastWriteTimeUtc(path); + var key = appId + "|" + path; + if (Cache.TryGetValue(key, out var cached) && cached.Stamp == stamp && DateTime.UtcNow - cached.Checked < TimeSpan.FromMinutes(5)) return cached.Trusted; + var trusted = Verify(path, appId); + Cache[key] = (stamp, DateTime.UtcNow, trusted); + return trusted; + } + catch (Exception error) when (error is IOException or UnauthorizedAccessException or System.Security.Cryptography.CryptographicException or ArgumentException) + { return false; } + } + + /// Asks Windows to verify the signed file and releases the native trust state. + private static bool Verify(string path, string appId) + { + var info = new FileInfoData { Size = (uint)Marshal.SizeOf(), Path = path }; + var pointer = Marshal.AllocHGlobal(Marshal.SizeOf()); + Marshal.StructureToPtr(info, pointer, false); + var data = new TrustData { Size = (uint)Marshal.SizeOf(), UiChoice = 2, UnionChoice = 1, + File = pointer, StateAction = 1, ProviderFlags = 0x1000 }; + var action = new Guid("00AAC56B-CD44-11d0-8CC2-00C04FC295EE"); + try + { + if (WinVerifyTrust(new IntPtr(-1), ref action, ref data) != 0) return false; + var provider = WTHelperProvDataFromStateData(data.State); + if (provider == IntPtr.Zero) return false; + var signer = WTHelperGetProvSignerFromChain(provider, 0, false, 0); + if (signer == IntPtr.Zero) return false; + var certificate = WTHelperGetProvCertFromChain(signer, 0); + if (certificate == IntPtr.Zero) return false; + var context = Marshal.ReadIntPtr(certificate, IntPtr.Size == 8 ? 8 : 4); + var name = new StringBuilder(512); + if (CertGetNameString(context, 4, 0, IntPtr.Zero, name, name.Capacity) <= 1) return false; + var publisher = name.ToString().Trim().TrimEnd('.'); + return appId.Equals("com.kakaoent.melon.player", StringComparison.OrdinalIgnoreCase) + ? publisher.Equals("Kakao Entertainment Corp", StringComparison.OrdinalIgnoreCase) + : publisher.Equals("Spotify AB", StringComparison.OrdinalIgnoreCase); + } + finally + { + data.StateAction = 2; + _ = WinVerifyTrust(new IntPtr(-1), ref action, ref data); + Marshal.DestroyStructure(pointer); + Marshal.FreeHGlobal(pointer); + } + } + + /// Native WINTRUST_FILE_INFO layout. + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + private struct FileInfoData { public uint Size; [MarshalAs(UnmanagedType.LPWStr)] public string Path; public IntPtr File; public IntPtr Subject; } + /// Native WINTRUST_DATA layout including optional signature settings. + [StructLayout(LayoutKind.Sequential)] + private struct TrustData + { + public uint Size; public IntPtr Policy; public IntPtr Sip; public uint UiChoice; public uint Revocation; + public uint UnionChoice; public IntPtr File; public uint StateAction; public IntPtr State; + public IntPtr Url; public uint ProviderFlags; public uint UiContext; public IntPtr SignatureSettings; + } + /// Validates a file under the system Authenticode policy. + [DllImport("wintrust.dll", ExactSpelling = true)] + private static extern int WinVerifyTrust(IntPtr window, ref Guid action, ref TrustData data); + /// Returns provider data for the verified Authenticode operation. + [DllImport("wintrust.dll", ExactSpelling = true)] private static extern IntPtr WTHelperProvDataFromStateData(IntPtr state); + /// Returns the primary verified signer rather than an unverified file claim. + [DllImport("wintrust.dll", ExactSpelling = true)] private static extern IntPtr WTHelperGetProvSignerFromChain(IntPtr provider, uint signer, [MarshalAs(UnmanagedType.Bool)] bool counterSigner, uint counterIndex); + /// Returns a certificate in the verified signer chain. + [DllImport("wintrust.dll", ExactSpelling = true)] private static extern IntPtr WTHelperGetProvCertFromChain(IntPtr signer, uint certificate); + /// Reads the publisher's display name from a Windows certificate context. + [DllImport("crypt32.dll", EntryPoint = "CertGetNameStringW", CharSet = CharSet.Unicode)] private static extern uint CertGetNameString(IntPtr certificate, uint type, uint flags, IntPtr typeData, StringBuilder name, int capacity); +} diff --git a/src/Reprise.Platform.Windows/README.md b/src/Reprise.Platform.Windows/README.md index 08c564a..71b1226 100644 --- a/src/Reprise.Platform.Windows/README.md +++ b/src/Reprise.Platform.Windows/README.md @@ -28,7 +28,13 @@ without synced lyrics the strip shows the track title and artist. Click it to open the player. General settings provide visibility and width controls. Taskbar settings include title format, cover style, and left/right placement. Left placement uses the measured gap between Widgets and centered application buttons and falls back to the right when there is no safe gap. Unreserved lyric widths ease over the same 280 ms as the upward line push. The strip follows taskbar DPI and system theme, and hides during fullscreen, taskbar autohide, or insufficient free space. The tray artwork setting also -controls the leading cover. Start, Search, and trusted Windows shell flyouts +controls the leading cover. Fullscreen detection uses physical DWM frame bounds +with a two-pixel rounding tolerance and the shell's exclusive Direct3D state. +The shell's generic busy state also suppresses a borderless foreground game. +Shell state applies only to the foreground monitor, so a game on a secondary +display does not hide lyrics on another display. Geometry remains a fallback +when the shell query fails, and a maximized work-area window is not fullscreen. +Start, Search, and trusted Windows shell flyouts do not count as fullscreen apps, even when their native surface covers the monitor. If the shell temporarily stops exposing tray accessibility geometry, the strip retains its last measured position only while that shell UI has focus diff --git a/src/Reprise.Platform.Windows/Taskbar/TaskbarFullscreenPolicy.cs b/src/Reprise.Platform.Windows/Taskbar/TaskbarFullscreenPolicy.cs index 4bc9c0d..6952b65 100644 --- a/src/Reprise.Platform.Windows/Taskbar/TaskbarFullscreenPolicy.cs +++ b/src/Reprise.Platform.Windows/Taskbar/TaskbarFullscreenPolicy.cs @@ -1,16 +1,46 @@ namespace Reprise.Platform.Windows.Taskbar; +/// Public shell notification states used to recognize exclusive games without inspecting their processes. +internal enum TaskbarNotificationState +{ + /// The native query failed or has not been performed. + Unknown = 0, + /// The user is away or the session is locked. + NotPresent = 1, + /// A fullscreen application or presentation prevents interruptions. + Busy = 2, + /// An exclusive Direct3D fullscreen application is running. + Direct3DFullscreen = 3, + /// The user explicitly enabled presentation settings. + Presentation = 4, + /// The shell currently accepts notifications. + AcceptsNotifications = 5, + /// The user is in the initial quiet period after setup. + QuietTime = 6, + /// A Windows Store application is running, without implying fullscreen. + App = 7, +} + /// Distinguishes genuine fullscreen apps from Windows shell surfaces that also span the monitor. internal static class TaskbarFullscreenPolicy { + /// Allows only small physical-pixel rounding gaps at fullscreen monitor edges. + private const int EdgeTolerance = 2; + /// Hides lyrics for a covering app, while keeping them available when Start, Search, or another trusted shell flyout has focus. - internal static bool ShouldHide(TaskbarRect monitor, TaskbarRect bounds, string windowClass, - string? processPath, string windowsDirectory) + internal static bool ShouldHide(TaskbarRect monitor, TaskbarRect? bounds, string windowClass, + string? processPath, string windowsDirectory, TaskbarNotificationState notificationState = TaskbarNotificationState.Unknown, + bool foregroundOnMonitor = false, bool borderless = false) { if (windowClass is "Progman" or "WorkerW" or "Shell_TrayWnd" or "Shell_SecondaryTrayWnd") return false; - if (bounds.Left > monitor.Left || bounds.Top > monitor.Top || - bounds.Right < monitor.Right || bounds.Bottom < monitor.Bottom) return false; - return !IsShellSurface(processPath, windowsDirectory); + if (IsShellSurface(processPath, windowsDirectory)) return false; + if (foregroundOnMonitor && (notificationState == TaskbarNotificationState.Direct3DFullscreen || + notificationState == TaskbarNotificationState.Busy && borderless)) return true; + return bounds is { Width: > 0, Height: > 0 } rectangle && + (long)rectangle.Left <= (long)monitor.Left + EdgeTolerance && + (long)rectangle.Top <= (long)monitor.Top + EdgeTolerance && + (long)rectangle.Right >= (long)monitor.Right - EdgeTolerance && + (long)rectangle.Bottom >= (long)monitor.Bottom - EdgeTolerance; } /// Recognizes specific shell hosts only inside the Windows installation, without excluding ordinary fullscreen CoreWindow apps. diff --git a/src/Reprise.Platform.Windows/Taskbar/WindowsTaskbarGeometry.cs b/src/Reprise.Platform.Windows/Taskbar/WindowsTaskbarGeometry.cs index c953fdd..720207a 100644 --- a/src/Reprise.Platform.Windows/Taskbar/WindowsTaskbarGeometry.cs +++ b/src/Reprise.Platform.Windows/Taskbar/WindowsTaskbarGeometry.cs @@ -82,7 +82,7 @@ internal static object[] Diagnose() return result.ToArray(); } - /// Hides the strip for genuine fullscreen apps, excluding monitor-sized Start and other trusted Windows shell surfaces. + /// Combines physical frame bounds with shell-reported fullscreen state, including exclusive games with different render resolutions. /// Monitor containing the taskbar. internal static bool IsFullscreen(TaskbarRect monitor) { @@ -91,11 +91,21 @@ internal static bool IsFullscreen(TaskbarRect monitor) var name = new StringBuilder(256); GetClassName(foreground, name, name.Capacity); GetWindowThreadProcessId(foreground, out var process); - if (process == Environment.ProcessId || !GetWindowRect(foreground, out var bounds)) return false; - if (bounds.Left > monitor.Left || bounds.Top > monitor.Top || - bounds.Right < monitor.Right || bounds.Bottom < monitor.Bottom) return false; - return TaskbarFullscreenPolicy.ShouldHide(monitor, Convert(bounds), name.ToString(), - ProcessPath(process), Environment.GetFolderPath(Environment.SpecialFolder.Windows)); + if (process == Environment.ProcessId) return false; + TaskbarRect? bounds = null; + // DWM reports physical pixels; GetWindowRect can be virtualized for another DPI context. + if (DwmGetWindowAttribute(foreground, 9, out var physicalBounds, Marshal.SizeOf()) >= 0) + bounds = Convert(physicalBounds); + else if (GetWindowRect(foreground, out var fallbackBounds)) + bounds = Convert(fallbackBounds); + var foregroundMonitor = new MonitorInfo { Size = Marshal.SizeOf() }; + var sameMonitor = GetMonitorInfo(MonitorFromWindow(foreground, 2), ref foregroundMonitor) && + Convert(foregroundMonitor.Monitor) == monitor; + var notification = SHQueryUserNotificationState(out var state) >= 0 ? state : TaskbarNotificationState.Unknown; + var borderless = (GetWindowLong(foreground, -16) & 0x00C40000) == 0; + return TaskbarFullscreenPolicy.ShouldHide(monitor, bounds, name.ToString(), + ProcessPath(process), Environment.GetFolderPath(Environment.SpecialFolder.Windows), + notification, sameMonitor, borderless); } /// Reads a foreground process image with limited query access, including across x86, x64, and ARM64 processes. @@ -175,6 +185,12 @@ private struct MonitorInfo { public int Size; public NativeRect Monitor, Work; p /// Reads native screen bounds. [DllImport("user32.dll")] private static extern bool GetWindowRect(nint window, out NativeRect rect); + /// Reads the visible frame in physical screen pixels without DPI virtualization. + [DllImport("dwmapi.dll")] + private static extern int DwmGetWindowAttribute(nint window, uint attribute, out NativeRect rect, int size); + /// Reads the shell's fullscreen notification state without opening or injecting into a game process. + [DllImport("shell32.dll")] + private static extern int SHQueryUserNotificationState(out TaskbarNotificationState state); /// Checks native visibility. [DllImport("user32.dll")] private static extern bool IsWindowVisible(nint window); diff --git a/tests/fixtures/windows/native-player/Program.cs b/tests/fixtures/windows/native-player/Program.cs index e4225df..b5ab0cc 100644 --- a/tests/fixtures/windows/native-player/Program.cs +++ b/tests/fixtures/windows/native-player/Program.cs @@ -55,7 +55,7 @@ internal static async Task RunAsync(string[] args) } if (args.Contains("--fullscreen-target")) { - await TaskbarVisibilityVerification.RunFullscreenTargetAsync(root); + await TaskbarVisibilityVerification.RunFullscreenTargetAsync(root, args.Contains("--inset-fullscreen")); return; } if (args.Contains("--verify-taskbar-fullscreen")) diff --git a/tests/fixtures/windows/native-player/README.md b/tests/fixtures/windows/native-player/README.md index e62d7bf..c442445 100644 --- a/tests/fixtures/windows/native-player/README.md +++ b/tests/fixtures/windows/native-player/README.md @@ -80,8 +80,11 @@ native taskbar geometry, accessibility status, and native strip visibility in `stop-visibility` file beside the fixture to stop early. `--observe-taskbar` records the same metadata briefly without creating a diagnostic strip. `--verify-taskbar-fullscreen` uses a fixture-owned fullscreen child process to -verify that genuine fullscreen content hides lyrics and returning to the -desktop restores them. Its result is `fullscreen-result.json`. +verify that genuine fullscreen content and a borderless surface inset by one +physical pixel hide lyrics, and returning to the desktop restores them after +each case. Its result is `fullscreen-result.json`. Exclusive Direct3D state and +mixed-monitor resolution cases are also covered by the fullscreen policy tests; +this fixture does not run a protected game or create an exclusive Direct3D device. To verify the production PowerShell/NSIS handoff without a network connection, first exit Reprise and run the fixture with `--verify-update update.json Setup.exe`. diff --git a/tests/fixtures/windows/native-player/TaskbarVisibilityVerification.cs b/tests/fixtures/windows/native-player/TaskbarVisibilityVerification.cs index 1338dd4..42aa592 100644 --- a/tests/fixtures/windows/native-player/TaskbarVisibilityVerification.cs +++ b/tests/fixtures/windows/native-player/TaskbarVisibilityVerification.cs @@ -11,7 +11,7 @@ /// Records real foreground and Reprise visibility without injecting input or changing another application's windows. internal static class TaskbarVisibilityVerification { - /// Verifies that a real fullscreen window in another process still hides lyrics and closing it restores them. + /// Verifies exact fullscreen and one-pixel inset windows hide lyrics, then restore them after each child exits. internal static async Task VerifyFullscreenAsync(string root) { using var publisher = new WindowsTaskbarLyricsPublisher(); @@ -39,32 +39,50 @@ internal static async Task VerifyFullscreenAsync(string root) await Task.Delay(250); } if (frame is null || strip is null) throw new InvalidOperationException("The diagnostic strip did not appear on the ordinary desktop."); - stage = "fullscreen child"; - var start = new ProcessStartInfo(Environment.ProcessPath!) { UseShellExecute = false }; - start.ArgumentList.Add("--fullscreen-target"); - target = Process.Start(start)!; - var detected = false; - for (var attempt = 0; attempt < 120; attempt++) - { - publisher.Publish(state); - GetWindowThreadProcessId(GetForegroundWindow(), out var foregroundProcess); - detected = foregroundProcess == target.Id && WindowsTaskbarGeometry.IsFullscreen(frame.Monitor); - if (detected && !strip.IsVisible) break; - await Task.Delay(250); - } - if (!detected || strip.IsVisible) throw new InvalidOperationException("The real fullscreen child did not suppress the strip."); - stage = "restore desktop"; - File.WriteAllText(Path.Combine(root, "stop-fullscreen"), "stop"); - await target.WaitForExitAsync().WaitAsync(TimeSpan.FromSeconds(10)); - control.Activate(); - for (var attempt = 0; attempt < 40 && !strip.IsVisible; attempt++) + var cases = new List(); + foreach (var inset in new[] { false, true }) { - publisher.Publish(state); - await Task.Delay(250); + File.Delete(Path.Combine(root, "stop-fullscreen")); + stage = inset ? "inset fullscreen child" : "fullscreen child"; + var start = new ProcessStartInfo(Environment.ProcessPath!) { UseShellExecute = false }; + start.ArgumentList.Add("--fullscreen-target"); + if (inset) start.ArgumentList.Add("--inset-fullscreen"); + target = Process.Start(start)!; + var detected = false; + for (var attempt = 0; attempt < 120; attempt++) + { + publisher.Publish(state); + GetWindowThreadProcessId(GetForegroundWindow(), out var foregroundProcess); + detected = foregroundProcess == target.Id && WindowsTaskbarGeometry.IsFullscreen(frame.Monitor); + if (detected && !strip.IsVisible) break; + await Task.Delay(250); + } + if (!detected || strip.IsVisible) + { + GetWindowThreadProcessId(GetForegroundWindow(), out var activeProcess); + GetWindowRect(GetForegroundWindow(), out var activeBounds); + var activeClass = new StringBuilder(256); + GetClassName(GetForegroundWindow(), activeClass, activeClass.Capacity); + throw new InvalidOperationException($"Fullscreen verification failed: foreground={activeProcess}, target={target.Id}, " + + $"class={activeClass}, bounds={activeBounds.Left},{activeBounds.Top},{activeBounds.Right},{activeBounds.Bottom}, " + + $"monitor={frame.Monitor}, detected={detected}, stripVisible={strip.IsVisible}."); + } + stage = "restore desktop"; + File.WriteAllText(Path.Combine(root, "stop-fullscreen"), "stop"); + await target.WaitForExitAsync().WaitAsync(TimeSpan.FromSeconds(10)); + control.Activate(); + for (var attempt = 0; attempt < 40 && !strip.IsVisible; attempt++) + { + publisher.Publish(state); + await Task.Delay(250); + } + if (!strip.IsVisible) throw new InvalidOperationException("The strip did not return after fullscreen ended."); + cases.Add(new { inset, fullscreenDetected = detected, hiddenDuringFullscreen = true, restored = strip.IsVisible }); + target.Dispose(); + target = null; } - if (!strip.IsVisible) throw new InvalidOperationException("The strip did not return after fullscreen ended."); File.WriteAllText(Path.Combine(root, "fullscreen-result.json"), JsonSerializer.Serialize(new - { ok = true, fullscreenDetected = detected, hiddenDuringFullscreen = true, restored = strip.IsVisible })); + { ok = true, cases })); } catch (Exception error) { @@ -83,10 +101,12 @@ internal static async Task VerifyFullscreenAsync(string root) } /// Runs only the fixture-owned fullscreen target; no other application's windows or keyboard input are modified. - internal static async Task RunFullscreenTargetAsync(string root) + internal static async Task RunFullscreenTargetAsync(string root, bool inset) { var window = new Window { Title = "Reprise fullscreen regression target", WindowDecorations = WindowDecorations.None, - ShowInTaskbar = false, Topmost = true, WindowState = WindowState.FullScreen, + CanResize = false, + ShowInTaskbar = false, Topmost = true, WindowState = inset ? WindowState.Normal : WindowState.FullScreen, + WindowStartupLocation = WindowStartupLocation.Manual, Background = Avalonia.Media.Brushes.MidnightBlue, Content = new TextBlock { Text = "Reprise 전체 화면 표시 검사", FontSize = 32, Foreground = Avalonia.Media.Brushes.White, @@ -95,6 +115,13 @@ internal static async Task RunFullscreenTargetAsync(string root) try { window.Show(); + if (inset) + { + var monitor = window.Screens.Primary!.Bounds; + window.Position = new PixelPoint(monitor.X + 1, monitor.Y + 1); + window.Width = (monitor.Width - 2) / window.RenderScaling; + window.Height = (monitor.Height - 2) / window.RenderScaling; + } window.Activate(); while (window.IsVisible && !File.Exists(Path.Combine(root, "stop-fullscreen"))) await Task.Delay(100); } diff --git a/tests/integration/windows/common/TaskbarFullscreenTests.cs b/tests/integration/windows/common/TaskbarFullscreenTests.cs index f7d4f28..5b39735 100644 --- a/tests/integration/windows/common/TaskbarFullscreenTests.cs +++ b/tests/integration/windows/common/TaskbarFullscreenTests.cs @@ -52,4 +52,69 @@ public void HonorsTheWindowsInstallationDirectory() Assert.False(TaskbarFullscreenPolicy.ShouldHide(monitor, monitor, "Windows.UI.Core.CoreWindow", @"D:\WINNT\SystemApps\Start\StartMenuExperienceHost.exe", @"D:\WINNT")); Assert.True(TaskbarFullscreenPolicy.ShouldHide(monitor, monitor, "Windows.UI.Core.CoreWindow", @"C:\Windows\SystemApps\Start\StartMenuExperienceHost.exe", @"D:\WINNT")); } + + /// Exclusive games hide lyrics even when their reported bounds use a different resolution or cannot be queried. + [Theory] + [InlineData(true)] + [InlineData(false)] + public void HidesExclusiveGameWithIncompleteWindowGeometry(bool readableBounds) + { + var monitor = new TaskbarRect(0, 0, 2560, 1440); + TaskbarRect? bounds = readableBounds ? new(0, 0, 1920, 1080) : null; + Assert.True(TaskbarFullscreenPolicy.ShouldHide(monitor, bounds, "UnrealWindow", null, @"C:\Windows", + TaskbarNotificationState.Direct3DFullscreen, foregroundOnMonitor: true)); + Assert.False(TaskbarFullscreenPolicy.ShouldHide(monitor, bounds, "UnrealWindow", null, @"C:\Windows", + TaskbarNotificationState.Direct3DFullscreen, foregroundOnMonitor: false)); + } + + /// The shell's generic busy state supports borderless games but cannot hide ordinary framed applications. + [Fact] + public void RequiresBorderlessForegroundForGenericBusyState() + { + var monitor = new TaskbarRect(-2560, -1440, 0, 0); + var bounds = new TaskbarRect(-2560, -1440, -640, -360); + Assert.True(TaskbarFullscreenPolicy.ShouldHide(monitor, bounds, "UnrealWindow", null, @"C:\Windows", + TaskbarNotificationState.Busy, foregroundOnMonitor: true, borderless: true)); + Assert.False(TaskbarFullscreenPolicy.ShouldHide(monitor, bounds, "UnrealWindow", null, @"C:\Windows", + TaskbarNotificationState.Busy, foregroundOnMonitor: true, borderless: false)); + Assert.False(TaskbarFullscreenPolicy.ShouldHide(monitor, bounds, "UnrealWindow", null, @"C:\Windows", + TaskbarNotificationState.Busy, foregroundOnMonitor: false, borderless: true)); + } + + /// Unrelated notification modes never turn a normal window into fullscreen content. + [Theory] + [InlineData((int)TaskbarNotificationState.Unknown)] + [InlineData((int)TaskbarNotificationState.NotPresent)] + [InlineData((int)TaskbarNotificationState.AcceptsNotifications)] + [InlineData((int)TaskbarNotificationState.QuietTime)] + [InlineData((int)TaskbarNotificationState.App)] + [InlineData((int)TaskbarNotificationState.Presentation)] + public void LeavesOrdinaryWindowsVisibleForUnrelatedNotificationStates(int state) + { + Assert.False(TaskbarFullscreenPolicy.ShouldHide(new(0, 0, 2560, 1440), new TaskbarRect(0, 0, 1280, 720), + "Chrome_WidgetWin_1", null, @"C:\Windows", (TaskbarNotificationState)state, foregroundOnMonitor: true, borderless: true)); + } + + /// Opening Start over a game and returning to the desktop preserve existing shell visibility behavior. + [Theory] + [InlineData((int)TaskbarNotificationState.Busy)] + [InlineData((int)TaskbarNotificationState.Direct3DFullscreen)] + public void PreservesShellExceptionsWhenFullscreenStateIsReported(int state) + { + var monitor = new TaskbarRect(0, 0, 2560, 1440); + Assert.False(TaskbarFullscreenPolicy.ShouldHide(monitor, monitor, "Windows.UI.Core.CoreWindow", + @"C:\Windows\SystemApps\Start\StartMenuExperienceHost.exe", @"C:\Windows", (TaskbarNotificationState)state, true, true)); + Assert.False(TaskbarFullscreenPolicy.ShouldHide(monitor, monitor, "WorkerW", null, @"C:\Windows", (TaskbarNotificationState)state, true, true)); + } + + /// Physical rounding gaps are accepted on negative-coordinate monitors without treating maximized work areas as fullscreen. + [Fact] + public void AcceptsOnlySmallMonitorEdgeGaps() + { + var monitor = new TaskbarRect(-2560, -1440, 0, 0); + Assert.True(TaskbarFullscreenPolicy.ShouldHide(monitor, new TaskbarRect(-2559, -1439, -1, -1), "UnrealWindow", null, @"C:\Windows")); + Assert.False(TaskbarFullscreenPolicy.ShouldHide(monitor, new TaskbarRect(-2560, -1440, 0, -48), "UnrealWindow", null, @"C:\Windows")); + Assert.False(TaskbarFullscreenPolicy.ShouldHide(monitor, new TaskbarRect(-2557, -1440, 0, 0), "UnrealWindow", null, @"C:\Windows")); + Assert.False(TaskbarFullscreenPolicy.ShouldHide(monitor, null, "UnrealWindow", null, @"C:\Windows")); + } }