diff --git a/README.md b/README.md index c9e7180..ec30eb4 100644 --- a/README.md +++ b/README.md @@ -71,16 +71,17 @@ Only apps that are playing take part; a paused app is skipped. For whatever is playing right now (the same as *Any app*): -| Variable | Value | -| ---------------------------------------------------------------------- | -------------------------------------------- | -| `system_media_app_name` | The playing app, e.g. `Firefox` | -| `system_media_track_name`, `system_media_artist`, `system_media_album` | Track metadata | -| `system_media_playback_state` | `playing`, `paused` or `stopped` | -| `system_media_is_playing` | `true` while playing | -| `system_media_position`, `system_media_duration` | Seconds; the position can be set to seek | -| `system_media_progress_percentage` | 0 to 100 | -| `system_media_volume` | The app's volume in percent; can be set | -| `system_media_shuffle_enabled`, `system_media_repeat_mode` | `repeat_mode` is `off`, `track` or `context` | +| Variable | Value | +| ---------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ | +| `system_media_app_name` | The playing app, e.g. `Firefox` | +| `system_media_track_name`, `system_media_artist`, `system_media_album` | Track metadata | +| `system_media_album_art_url` | The cover as a Macro Deck address, e.g. for a custom button; the app icon if there is none | +| `system_media_playback_state` | `playing`, `paused` or `stopped` | +| `system_media_is_playing` | `true` while playing | +| `system_media_position`, `system_media_duration` | Seconds; the position can be set to seek | +| `system_media_progress_percentage` | 0 to 100 | +| `system_media_volume` | The app's volume in percent; can be set | +| `system_media_shuffle_enabled`, `system_media_repeat_mode` | `repeat_mode` is `off`, `track` or `context` | Every app listed as an instance also has its own copy of these, except the app name, so a "Now Playing" text can follow one player while another plays too. They are in a folder per app in the variable picker, e.g. diff --git a/src/SystemMedia/Localization/Strings.resx b/src/SystemMedia/Localization/Strings.resx index 6bbeab3..0ca4aae 100644 --- a/src/SystemMedia/Localization/Strings.resx +++ b/src/SystemMedia/Localization/Strings.resx @@ -73,6 +73,9 @@ Album + + Album art URL + Playback state @@ -106,6 +109,9 @@ {app}: Album + + {app}: Album art URL + {app}: Playback state diff --git a/src/SystemMedia/PluginIntegration.cs b/src/SystemMedia/PluginIntegration.cs index 7d43087..38c85a6 100644 --- a/src/SystemMedia/PluginIntegration.cs +++ b/src/SystemMedia/PluginIntegration.cs @@ -46,6 +46,7 @@ public sealed class PluginIntegration private readonly CompositeMediaPlatform _platform; private readonly CurrentAppSelection _selection; private readonly IPluginCatalogNotifier _catalog; + private readonly string _pluginId; private readonly KnownAppsStore _store; private readonly PluginSettingsStore _settings; private readonly ThumbnailHistory _thumbnails; @@ -63,9 +64,10 @@ public sealed class PluginIntegration private volatile KnownApp[] _apps = []; private bool _rememberedAppsLoaded; - public PluginIntegration(IPluginCatalogNotifier catalog, IOptions hostOptions, ILogger logger) + public PluginIntegration(IPluginCatalogNotifier catalog, IOptions hostOptions, PluginMetadata metadata, ILogger logger) { _catalog = catalog; + _pluginId = metadata.Id; _logger = logger.ForContext(); var dataDirectory = hostOptions.Value.DataDirectory; var demo = false; @@ -196,11 +198,11 @@ public async ValueTask ReadAsync(string localId, CancellationTo if (FindAppVariable(localId) is var (app, currentId)) { - return SystemMediaVariables.Read(currentId, await app.State.GetAsync(cancellationToken)); + return SystemMediaVariables.Read(currentId, await app.State.GetAsync(cancellationToken), QualifiedPlayerId(app.InstanceId)); } var state = await _currentState.GetAsync(cancellationToken); - return SystemMediaVariables.Read(localId, state); + return SystemMediaVariables.Read(localId, state, QualifiedPlayerId(InstanceIds.Current)); } public ValueTask SetValueAsync(string localId, object? value, CancellationToken cancellationToken = default) @@ -276,13 +278,16 @@ private async Task> ReadAppVariablesAsync(IReadOnly { if (FindAppVariable(localId) is var (app, currentId)) { - values.Add(VariableValue.Of(localId, SystemMediaVariables.Read(currentId, await app.State.GetAsync(cancellationToken)))); + var state = await app.State.GetAsync(cancellationToken); + values.Add(VariableValue.Of(localId, SystemMediaVariables.Read(currentId, state, QualifiedPlayerId(app.InstanceId)))); } } return values; } + private string QualifiedPlayerId(string instanceId) => SystemMediaVariables.QualifiedPlayerId(_pluginId, instanceId); + private static IReadOnlyList AppVariablesOf(KnownApp[] apps, KnownApp app) => SystemMediaVariables.ForApp( app.InstanceId, diff --git a/src/SystemMedia/Variables/SystemMediaVariables.cs b/src/SystemMedia/Variables/SystemMediaVariables.cs index ced7635..25a5b14 100644 --- a/src/SystemMedia/Variables/SystemMediaVariables.cs +++ b/src/SystemMedia/Variables/SystemMediaVariables.cs @@ -13,6 +13,7 @@ internal static class SystemMediaVariables internal const string VolumeId = "system-media-volume"; private const string IdPrefix = "system-media-"; + private const string ArtworkPath = "/api/music-player/artwork/"; private static readonly TimeSpan _fast = TimeSpan.FromSeconds(1); private static readonly TimeSpan _normal = TimeSpan.FromSeconds(2); @@ -24,6 +25,9 @@ internal static class SystemMediaVariables Text("system_media_track_name", Strings.Variables.TrackName(), state => state.TrackName), Text("system_media_artist", Strings.Variables.Artist(), state => state.Artists.Count == 0 ? null : string.Join(", ", state.Artists)), Text("system_media_album", Strings.Variables.Album(), state => state.AlbumName), + new(VariableDefinition.Eager("system_media_album_art_url", VariableType.Text, refreshInterval: _normal) + with { DisplayName = Strings.Variables.AlbumArtUrl() }, + ArtworkUrl), Text("system_media_playback_state", Strings.Variables.PlaybackState(), state => state.PlaybackState.ToString().ToLowerInvariant()), new(VariableDefinition.Eager("system_media_is_playing", VariableType.Boolean, refreshInterval: _normal) with { DisplayName = Strings.Variables.IsPlaying() }, @@ -75,6 +79,7 @@ internal static class SystemMediaVariables ["system_media_track_name"] = Strings.Variables.App.TrackName, ["system_media_artist"] = Strings.Variables.App.Artist, ["system_media_album"] = Strings.Variables.App.Album, + ["system_media_album_art_url"] = Strings.Variables.App.AlbumArtUrl, ["system_media_playback_state"] = Strings.Variables.App.PlaybackState, ["system_media_is_playing"] = Strings.Variables.App.IsPlaying, ["system_media_position"] = Strings.Variables.App.Position, @@ -148,7 +153,10 @@ internal static bool Matches(VariableDefinition variable, string appName, string internal static AudioDeviceRole? DeviceRole(string localId) => Array.Find(_devices, candidate => string.Equals(candidate.Definition.ResolvedId, localId, StringComparison.Ordinal))?.Role; - internal static VariableReading Read(string localId, MusicPlayerState state) + // The host only finds the player under the id qualified with the plugin's own. + internal static string QualifiedPlayerId(string pluginId, string instanceId) => $"{pluginId}::{instanceId}"; + + internal static VariableReading Read(string localId, MusicPlayerState state, string qualifiedPlayerId) { var entry = Array.Find(_entries, candidate => string.Equals(candidate.Definition.ResolvedId, localId, StringComparison.Ordinal)); if (entry is null) @@ -156,7 +164,7 @@ internal static VariableReading Read(string localId, MusicPlayerState state) return VariableReading.Unavailable; } - var value = entry.Read(state); + var value = entry.Read(state, qualifiedPlayerId); return localId switch { VolumeId => VariableReading.Of(value, 0, 100, 1), @@ -170,6 +178,12 @@ internal static VariableReading Read(string localId, MusicPlayerState state) ? (int)Math.Clamp(Math.Round(position / duration * 100), 0, 100) : null; + // The host's own endpoint, not the source: it serves the same image the Music Player widget shows. + private static string? ArtworkUrl(MusicPlayerState state, string qualifiedPlayerId) => + state.ArtworkId is { } artworkId + ? $"{ArtworkPath}{Uri.EscapeDataString(artworkId)}?instanceId={Uri.EscapeDataString(qualifiedPlayerId)}" + : null; + private static Entry Text(string name, LocalizedText displayName, Func read, TimeSpan? refresh = null) => new(VariableDefinition.Eager(name, VariableType.Text, refreshInterval: refresh ?? _normal) with { DisplayName = displayName }, read); @@ -182,7 +196,13 @@ private static string WithHash(string slug, string instanceId) private static string AppVariableId(string instanceId, string currentId) => $"{AppFolderId(instanceId)}-{currentId[IdPrefix.Length..]}"; - private sealed record Entry(VariableDefinition Definition, Func Read); + private sealed record Entry(VariableDefinition Definition, Func Read) + { + public Entry(VariableDefinition definition, Func read) + : this(definition, (state, _) => read(state)) + { + } + } private static DeviceEntry Device(string name, LocalizedText displayName, AudioDeviceRole role) => new(VariableDefinition.Eager(name, VariableType.Text, refreshInterval: _slow) diff --git a/tests/SystemMedia.Tests/SystemMediaVariablesTests.cs b/tests/SystemMedia.Tests/SystemMediaVariablesTests.cs index fc32e3f..9cc645d 100644 --- a/tests/SystemMedia.Tests/SystemMediaVariablesTests.cs +++ b/tests/SystemMedia.Tests/SystemMediaVariablesTests.cs @@ -11,6 +11,8 @@ namespace SystemMedia.Tests; [TestFixture] public sealed class SystemMediaVariablesTests { + private const string CurrentPlayer = "com.pyflat.system-media::current"; + private static readonly MusicPlayerState _playing = new() { IsConnected = true, @@ -44,7 +46,7 @@ public void Every_variable_has_a_valid_id_and_a_display_name() [TestCase("system-media-repeat-mode", "context")] public void A_variable_reads_its_value_from_the_current_state(string id, object expected) { - Assert.That(SystemMediaVariables.Read(id, _playing).Value, Is.EqualTo(expected)); + Assert.That(SystemMediaVariables.Read(id, _playing, CurrentPlayer).Value, Is.EqualTo(expected)); } [TestCase("system-media-output-device", nameof(AudioDeviceRole.Output))] @@ -68,7 +70,7 @@ public void A_state_variable_is_no_device() [Test] public void The_position_slider_ends_at_the_track_duration() { - var reading = SystemMediaVariables.Read(SystemMediaVariables.PositionId, _playing); + var reading = SystemMediaVariables.Read(SystemMediaVariables.PositionId, _playing, CurrentPlayer); Assert.That(reading.Max, Is.EqualTo(256)); } @@ -160,11 +162,40 @@ public void An_app_folder_holds_variables_but_is_none() Assert.That(folder.IsBindable, Is.False); } + // Pinned: the host's artwork endpoint looks the player up by this exact id. + [Test] + public void The_player_id_is_qualified_with_the_plugin_id() + { + Assert.That(SystemMediaVariables.QualifiedPlayerId("com.pyflat.system-media", "app-spotify-exe-b527fa0a"), Is.EqualTo("com.pyflat.system-media::app-spotify-exe-b527fa0a")); + } + + [Test] + public void The_album_art_url_points_at_the_hosts_artwork_endpoint() + { + var state = _playing with { ArtworkId = "art-0123456789abcdef" }; + + Assert.That( + SystemMediaVariables.Read("system-media-album-art-url", state, "com.pyflat.system-media::app-vlc@web-2900ecd1").Value, + Is.EqualTo("/api/music-player/artwork/art-0123456789abcdef?instanceId=com.pyflat.system-media%3A%3Aapp-vlc%40web-2900ecd1")); + } + + [Test] + public void A_track_without_artwork_has_no_album_art_url() + { + Assert.That(SystemMediaVariables.Read("system-media-album-art-url", _playing, CurrentPlayer).Value, Is.Null); + } + + [Test] + public void An_app_album_art_url_reads_like_the_any_app_one() + { + Assert.That(SystemMediaVariables.CurrentIdOf("system-media-app-spotify-exe-b527fa0a-album-art-url", "app-spotify-exe-b527fa0a"), Is.EqualTo("system-media-album-art-url")); + } + [Test] public void A_stream_without_a_timeline_has_no_progress() { var stream = _playing with { Position = null, Duration = null }; - Assert.That(SystemMediaVariables.Read("system-media-progress-percentage", stream).Value, Is.Null); + Assert.That(SystemMediaVariables.Read("system-media-progress-percentage", stream, CurrentPlayer).Value, Is.Null); } }