Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 11 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
6 changes: 6 additions & 0 deletions src/SystemMedia/Localization/Strings.resx
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,9 @@
<data name="Variables.Album" xml:space="preserve">
<value>Album</value>
</data>
<data name="Variables.AlbumArtUrl" xml:space="preserve">
<value>Album art URL</value>
</data>
<data name="Variables.PlaybackState" xml:space="preserve">
<value>Playback state</value>
</data>
Expand Down Expand Up @@ -106,6 +109,9 @@
<data name="Variables.App.Album" xml:space="preserve">
<value>{app}: Album</value>
</data>
<data name="Variables.App.AlbumArtUrl" xml:space="preserve">
<value>{app}: Album art URL</value>
</data>
<data name="Variables.App.PlaybackState" xml:space="preserve">
<value>{app}: Playback state</value>
</data>
Expand Down
13 changes: 9 additions & 4 deletions src/SystemMedia/PluginIntegration.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -63,9 +64,10 @@ public sealed class PluginIntegration
private volatile KnownApp[] _apps = [];
private bool _rememberedAppsLoaded;

public PluginIntegration(IPluginCatalogNotifier catalog, IOptions<PluginHostOptions> hostOptions, ILogger logger)
public PluginIntegration(IPluginCatalogNotifier catalog, IOptions<PluginHostOptions> hostOptions, PluginMetadata metadata, ILogger logger)
{
_catalog = catalog;
_pluginId = metadata.Id;
_logger = logger.ForContext<PluginIntegration>();
var dataDirectory = hostOptions.Value.DataDirectory;
var demo = false;
Expand Down Expand Up @@ -196,11 +198,11 @@ public async ValueTask<VariableReading> 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<VariableWriteResult> SetValueAsync(string localId, object? value, CancellationToken cancellationToken = default)
Expand Down Expand Up @@ -276,13 +278,16 @@ private async Task<IReadOnlyList<VariableValue>> 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<VariableDefinition> AppVariablesOf(KnownApp[] apps, KnownApp app) =>
SystemMediaVariables.ForApp(
app.InstanceId,
Expand Down
26 changes: 23 additions & 3 deletions src/SystemMedia/Variables/SystemMediaVariables.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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() },
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -148,15 +153,18 @@ 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)
{
return VariableReading.Unavailable;
}

var value = entry.Read(state);
var value = entry.Read(state, qualifiedPlayerId);
return localId switch
{
VolumeId => VariableReading.Of(value, 0, 100, 1),
Expand All @@ -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<MusicPlayerState, object?> read, TimeSpan? refresh = null) =>
new(VariableDefinition.Eager(name, VariableType.Text, refreshInterval: refresh ?? _normal) with { DisplayName = displayName }, read);

Expand All @@ -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<MusicPlayerState, object?> Read);
private sealed record Entry(VariableDefinition Definition, Func<MusicPlayerState, string, object?> Read)
{
public Entry(VariableDefinition definition, Func<MusicPlayerState, object?> read)
: this(definition, (state, _) => read(state))
{
}
}

private static DeviceEntry Device(string name, LocalizedText displayName, AudioDeviceRole role) =>
new(VariableDefinition.Eager(name, VariableType.Text, refreshInterval: _slow)
Expand Down
37 changes: 34 additions & 3 deletions tests/SystemMedia.Tests/SystemMediaVariablesTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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))]
Expand All @@ -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));
}
Expand Down Expand Up @@ -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);
}
}
Loading