Implement Watched Together shared viewing accounts
🏗️ Build Plugin / build (push) Has been cancelled
🧪 Test Plugin / test (push) Has been cancelled

Replaces the plugin template with a working plugin that lets several
users share one viewing account while keeping their individual watched
lists accurate.

Three pieces:

- Auto-creating groups. Logging in as "alice+bob" with any named
  member's own password provisions the shared account and signs you in.
  Verified against 10.11.5: AuthenticateUser offers unmatched usernames
  to every enabled provider and re-queries afterwards, which is the hook
  this relies on. Gated on a real member password so knowing two
  usernames is not enough to create an account.

- Multi-password authentication. IRequiresResolvedUser hands us the
  resolved shared account; each member's live stored hash is checked via
  ICryptoProvider.Verify. Deliberately avoids re-entering
  UserManager.AuthenticateUser, which would trip every member's
  failed-attempt counter whenever a different member's password matched.

- One-way played-state sync. Shared account to members only, filtered to
  PlaybackFinished/TogglePlayed/Import so playback progress ticks are
  ignored. No loop guard needed: member writes carry a non-shared id.

Membership is stored as user IDs rather than re-parsed from the username,
so shared accounts can be renamed freely. The +/name collision resolves
itself because Jellyfin only consults the plugin when no local user
matches the typed name.

Targets Jellyfin 10.11.x / net9.0. Adds Gitea CI (test, build, release),
a builder image, and 34 tests covering the auth and sync rules.
This commit is contained in:
2026-07-29 00:00:13 +02:00
parent 7a9dbdafcc
commit 7be07d16a2
46 changed files with 3319 additions and 690 deletions
@@ -0,0 +1,216 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Jellyfin.Database.Implementations.Entities;
using Jellyfin.Plugin.WatchedTogether.Auth;
using Jellyfin.Plugin.WatchedTogether.Configuration;
using Jellyfin.Plugin.WatchedTogether.Services;
using MediaBrowser.Controller.Authentication;
using MediaBrowser.Model.Cryptography;
using Microsoft.Extensions.Logging.Abstractions;
using Moq;
using Xunit;
namespace Jellyfin.Plugin.WatchedTogether.Tests;
/// <summary>
/// Covers the rule that makes this plugin work: any member's password unlocks the shared account,
/// and nothing else does.
/// </summary>
public class AuthenticationTests
{
// PasswordHash.Parse requires hex-encoded salt and hash segments, so these fixtures use real
// hex rather than readable placeholders.
private const string AliceHash = "$PBKDF2-SHA512$iterations=210000$A1A1A1A1$AAAAAAAABBBBBBBB";
private const string BobHash = "$PBKDF2-SHA512$iterations=210000$B2B2B2B2$CCCCCCCCDDDDDDDD";
private static User MakeUser(string name, string? password)
{
var user = new User(name, "Prov", "ResetProv") { Password = password! };
return user;
}
/// <summary>
/// Builds a provider whose crypto accepts exactly the (hash, password) pairs given.
/// </summary>
private static SharedAccountAuthenticationProvider MakeProvider(
SharedGroup? group,
IReadOnlyList<User> members,
params (string Hash, string Password)[] validPairs)
=> MakeProvider(group, members, null, validPairs);
/// <summary>
/// Builds a provider, optionally with a dynamic-group service that returns
/// <paramref name="dynamicResult"/> for an unresolved username.
/// </summary>
private static SharedAccountAuthenticationProvider MakeProvider(
SharedGroup? group,
IReadOnlyList<User> members,
DynamicGroupResult? dynamicResult,
params (string Hash, string Password)[] validPairs)
{
// ICryptoProvider.Verify takes a ReadOnlySpan<char>, which Moq cannot express as a generic
// argument, so the crypto provider is stubbed by hand.
var crypto = new StubCryptoProvider(validPairs);
var groups = new Mock<IGroupService>();
groups.Setup(g => g.GetGroupForSharedUser(It.IsAny<Guid>())).Returns(group);
groups.Setup(g => g.GetEligibleMembers(It.IsAny<SharedGroup>())).Returns(members);
var dynamic = new Mock<IDynamicGroupService>();
dynamic.Setup(d => d.TryCreateFromLoginAsync(It.IsAny<string>(), It.IsAny<string>()))
.ReturnsAsync(dynamicResult);
return new SharedAccountAuthenticationProvider(
crypto,
groups.Object,
dynamic.Object,
NullLogger<SharedAccountAuthenticationProvider>.Instance);
}
[Fact]
public async Task Authenticate_WithFirstMemberPassword_Succeeds()
{
var alice = MakeUser("alice", AliceHash);
var bob = MakeUser("bob", BobHash);
var shared = MakeUser("alice+bob", null);
var group = new SharedGroup { SharedUserId = shared.Id, MemberUserIds = [alice.Id, bob.Id] };
var provider = MakeProvider(group, [alice, bob], (AliceHash, "alice-pw"));
var result = await provider.Authenticate("alice+bob", "alice-pw", shared);
Assert.Equal("alice+bob", result.Username);
}
[Fact]
public async Task Authenticate_WithLaterMemberPassword_Succeeds()
{
// The second member's password must work even though the first member's check failed
// first - that loop is the whole point of the plugin.
var alice = MakeUser("alice", AliceHash);
var bob = MakeUser("bob", BobHash);
var shared = MakeUser("alice+bob", null);
var group = new SharedGroup { SharedUserId = shared.Id, MemberUserIds = [alice.Id, bob.Id] };
var provider = MakeProvider(group, [alice, bob], (BobHash, "bob-pw"));
var result = await provider.Authenticate("alice+bob", "bob-pw", shared);
Assert.Equal("alice+bob", result.Username);
}
[Fact]
public async Task Authenticate_WithWrongPassword_Throws()
{
var alice = MakeUser("alice", AliceHash);
var bob = MakeUser("bob", BobHash);
var shared = MakeUser("alice+bob", null);
var group = new SharedGroup { SharedUserId = shared.Id, MemberUserIds = [alice.Id, bob.Id] };
var provider = MakeProvider(group, [alice, bob], (AliceHash, "alice-pw"));
await Assert.ThrowsAsync<AuthenticationException>(
() => provider.Authenticate("alice+bob", "not-the-password", shared));
}
[Fact]
public async Task Authenticate_WhenGroupDisabledOrUnknown_Throws()
{
// GetGroupForSharedUser returns null both for accounts we do not manage and for groups an
// admin has suspended. Neither may be unlocked.
var shared = MakeUser("alice+bob", null);
var provider = MakeProvider(null, [], (AliceHash, "alice-pw"));
await Assert.ThrowsAsync<AuthenticationException>(
() => provider.Authenticate("alice+bob", "alice-pw", shared));
}
[Fact]
public async Task Authenticate_WhenNoEligibleMembers_Throws()
{
// Every member disabled or deleted: a correct password for a now-disabled member must not
// still open the account.
var shared = MakeUser("alice+bob", null);
var group = new SharedGroup { SharedUserId = shared.Id, MemberUserIds = [Guid.NewGuid()] };
var provider = MakeProvider(group, [], (AliceHash, "alice-pw"));
await Assert.ThrowsAsync<AuthenticationException>(
() => provider.Authenticate("alice+bob", "alice-pw", shared));
}
[Fact]
public async Task Authenticate_MemberWithNoPassword_IsSkipped()
{
// A passwordless member contributes no credential; an empty submitted password must not
// match them and unlock the account.
var ghost = MakeUser("ghost", null);
var bob = MakeUser("bob", BobHash);
var shared = MakeUser("ghost+bob", null);
var group = new SharedGroup { SharedUserId = shared.Id, MemberUserIds = [ghost.Id, bob.Id] };
var provider = MakeProvider(group, [ghost, bob], (BobHash, "bob-pw"));
await Assert.ThrowsAsync<AuthenticationException>(
() => provider.Authenticate("ghost+bob", string.Empty, shared));
}
[Fact]
public async Task Authenticate_WithNullResolvedUser_AndNoDynamicMatch_Throws()
{
// Nothing resolved and the name is not a valid member combination.
var provider = MakeProvider(null, [], dynamicResult: null, (AliceHash, "alice-pw"));
await Assert.ThrowsAsync<AuthenticationException>(
() => provider.Authenticate("whoever", "alice-pw", null));
}
[Fact]
public async Task Authenticate_WithNullResolvedUser_CreatesGroupOnDemand()
{
// Typing "alice+bob" with a member's password provisions the shared account and logs in.
var group = new SharedGroup { SharedUserId = Guid.NewGuid() };
var provider = MakeProvider(
null,
[],
new DynamicGroupResult(group, "alice+bob"),
(AliceHash, "alice-pw"));
var result = await provider.Authenticate("alice+bob", "alice-pw", null);
Assert.Equal("alice+bob", result.Username);
}
[Fact]
public async Task Authenticate_TwoArgOverload_AlsoCreatesGroupOnDemand()
{
// The two-argument overload is equivalent to passing a null resolved user.
var group = new SharedGroup { SharedUserId = Guid.NewGuid() };
var provider = MakeProvider(
null,
[],
new DynamicGroupResult(group, "alice+bob"),
(AliceHash, "alice-pw"));
var result = await provider.Authenticate("alice+bob", "alice-pw");
Assert.Equal("alice+bob", result.Username);
}
[Fact]
public void HasPassword_IsAlwaysTrue()
{
// Returning false would let a client offer a passwordless login for the shared account.
var provider = MakeProvider(null, []);
Assert.True(provider.HasPassword(MakeUser("alice+bob", null)));
}
[Fact]
public async Task ChangePassword_IsNotSupported()
{
var provider = MakeProvider(null, []);
await Assert.ThrowsAsync<NotSupportedException>(
() => provider.ChangePassword(MakeUser("alice+bob", null), "new-pw"));
}
}
@@ -0,0 +1,237 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Jellyfin.Data;
using Jellyfin.Database.Implementations.Entities;
using Jellyfin.Database.Implementations.Enums;
using Jellyfin.Plugin.WatchedTogether.Configuration;
using Jellyfin.Plugin.WatchedTogether.Services;
using MediaBrowser.Controller.Library;
using Microsoft.Extensions.Logging.Abstractions;
using Moq;
using Xunit;
namespace Jellyfin.Plugin.WatchedTogether.Tests;
/// <summary>
/// Covers creating a shared account on the fly from a name typed at the login screen.
/// </summary>
/// <remarks>
/// These tests drive <see cref="DynamicGroupService"/> through a stubbed user manager. They rely on
/// <see cref="Plugin.Instance"/> configuration, which is set up per test via
/// <see cref="PluginTestContext"/>.
/// </remarks>
[Collection(nameof(PluginTestContext))]
public class DynamicGroupTests
{
private const string AliceHash = "$PBKDF2-SHA512$iterations=210000$A1A1A1A1$AAAAAAAABBBBBBBB";
private const string BobHash = "$PBKDF2-SHA512$iterations=210000$B2B2B2B2$CCCCCCCCDDDDDDDD";
private static User MakeUser(string name, string? password = null, bool disabled = false)
{
var user = new User(name, "Prov", "ResetProv");
if (password is not null)
{
user.Password = password;
}
if (disabled)
{
user.SetPermission(PermissionKind.IsDisabled, true);
}
return user;
}
private sealed record Harness(
DynamicGroupService Service,
Mock<IProvisioningService> Provisioning);
private static Harness MakeService(
IReadOnlyList<User> knownUsers,
params (string Hash, string Password)[] validPairs)
{
var userManager = new Mock<IUserManager>();
userManager.Setup(m => m.GetUserByName(It.IsAny<string>()))
.Returns((string n) =>
{
foreach (var u in knownUsers)
{
if (string.Equals(u.Username, n, StringComparison.OrdinalIgnoreCase))
{
return u;
}
}
return null!;
});
var provisioning = new Mock<IProvisioningService>();
var createdShared = MakeUser("created-shared");
provisioning.Setup(p => p.CreateGroupAsync(
It.IsAny<IReadOnlyList<Guid>>(),
It.IsAny<string?>(),
It.IsAny<bool>(),
It.IsAny<IReadOnlyList<Guid>?>()))
.ReturnsAsync((IReadOnlyList<Guid> ids, string? name, bool _, IReadOnlyList<Guid>? _) =>
new SharedGroup { SharedUserId = createdShared.Id, MemberUserIds = [.. ids] });
userManager.Setup(m => m.GetUserById(createdShared.Id)).Returns(createdShared);
var service = new DynamicGroupService(
userManager.Object,
provisioning.Object,
new StubCryptoProvider(validPairs),
NullLogger<DynamicGroupService>.Instance);
return new Harness(service, provisioning);
}
[Fact]
public async Task TypingTwoMemberNames_WithAMemberPassword_CreatesTheAccount()
{
using var ctx = PluginTestContext.Create();
var alice = MakeUser("alice", AliceHash);
var bob = MakeUser("bob", BobHash);
var h = MakeService([alice, bob], (AliceHash, "alice-pw"));
var result = await h.Service.TryCreateFromLoginAsync("alice+bob", "alice-pw");
Assert.NotNull(result);
h.Provisioning.Verify(
p => p.CreateGroupAsync(
It.Is<IReadOnlyList<Guid>>(ids => ids.Count == 2),
"alice+bob",
It.IsAny<bool>(),
It.IsAny<IReadOnlyList<Guid>?>()),
Times.Once);
}
[Fact]
public async Task AnyNamedMembersPassword_Works()
{
using var ctx = PluginTestContext.Create();
var alice = MakeUser("alice", AliceHash);
var bob = MakeUser("bob", BobHash);
var h = MakeService([alice, bob], (BobHash, "bob-pw"));
Assert.NotNull(await h.Service.TryCreateFromLoginAsync("alice+bob", "bob-pw"));
}
[Fact]
public async Task WithoutAMatchingPassword_NothingIsCreated()
{
// Otherwise anyone who knows two usernames could conjure a shared account into existence.
using var ctx = PluginTestContext.Create();
var alice = MakeUser("alice", AliceHash);
var bob = MakeUser("bob", BobHash);
var h = MakeService([alice, bob], (AliceHash, "alice-pw"));
Assert.Null(await h.Service.TryCreateFromLoginAsync("alice+bob", "guessing"));
h.Provisioning.VerifyNoOtherCalls();
}
[Fact]
public async Task AnUnknownNamePart_IsRejected()
{
using var ctx = PluginTestContext.Create();
var alice = MakeUser("alice", AliceHash);
var h = MakeService([alice], (AliceHash, "alice-pw"));
Assert.Null(await h.Service.TryCreateFromLoginAsync("alice+nobody", "alice-pw"));
h.Provisioning.VerifyNoOtherCalls();
}
[Fact]
public async Task ADisabledMember_IsRejected()
{
using var ctx = PluginTestContext.Create();
var alice = MakeUser("alice", AliceHash);
var bob = MakeUser("bob", BobHash, disabled: true);
var h = MakeService([alice, bob], (AliceHash, "alice-pw"));
Assert.Null(await h.Service.TryCreateFromLoginAsync("alice+bob", "alice-pw"));
}
[Fact]
public async Task ASingleName_IsNotAGroup()
{
using var ctx = PluginTestContext.Create();
var alice = MakeUser("alice", AliceHash);
var h = MakeService([alice], (AliceHash, "alice-pw"));
Assert.Null(await h.Service.TryCreateFromLoginAsync("alice", "alice-pw"));
}
[Fact]
public async Task TheSameMemberTwice_IsRejected()
{
using var ctx = PluginTestContext.Create();
var alice = MakeUser("alice", AliceHash);
var h = MakeService([alice], (AliceHash, "alice-pw"));
Assert.Null(await h.Service.TryCreateFromLoginAsync("alice+alice", "alice-pw"));
}
[Fact]
public async Task AnExistingSharedAccountNamedPart_IsRejected()
{
// Shared accounts must not nest inside other shared accounts.
using var ctx = PluginTestContext.Create();
var alice = MakeUser("alice", AliceHash);
var existingShared = MakeUser("shared", BobHash);
ctx.Configuration.Groups.Add(new SharedGroup { SharedUserId = existingShared.Id });
var h = MakeService([alice, existingShared], (AliceHash, "alice-pw"));
Assert.Null(await h.Service.TryCreateFromLoginAsync("alice+shared", "alice-pw"));
}
[Fact]
public async Task WhenDisabledInConfiguration_NothingIsCreated()
{
using var ctx = PluginTestContext.Create();
ctx.Configuration.EnableDynamicGroups = false;
var alice = MakeUser("alice", AliceHash);
var bob = MakeUser("bob", BobHash);
var h = MakeService([alice, bob], (AliceHash, "alice-pw"));
Assert.Null(await h.Service.TryCreateFromLoginAsync("alice+bob", "alice-pw"));
}
[Fact]
public async Task AConfiguredSeparator_IsHonoured()
{
using var ctx = PluginTestContext.Create();
ctx.Configuration.NameSeparator = "_";
var alice = MakeUser("alice", AliceHash);
var bob = MakeUser("bob", BobHash);
var h = MakeService([alice, bob], (AliceHash, "alice-pw"));
Assert.NotNull(await h.Service.TryCreateFromLoginAsync("alice_bob", "alice-pw"));
Assert.Null(await h.Service.TryCreateFromLoginAsync("alice+bob", "alice-pw"));
}
[Fact]
public async Task ThreeOrMoreMembers_AreSupported()
{
using var ctx = PluginTestContext.Create();
var alice = MakeUser("alice", AliceHash);
var bob = MakeUser("bob", BobHash);
var carol = MakeUser("carol", BobHash);
var h = MakeService([alice, bob, carol], (AliceHash, "alice-pw"));
Assert.NotNull(await h.Service.TryCreateFromLoginAsync("alice+bob+carol", "alice-pw"));
h.Provisioning.Verify(
p => p.CreateGroupAsync(
It.Is<IReadOnlyList<Guid>>(ids => ids.Count == 3),
It.IsAny<string?>(),
It.IsAny<bool>(),
It.IsAny<IReadOnlyList<Guid>?>()),
Times.Once);
}
}
@@ -0,0 +1,41 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
<!-- Test code is exempt from the strict analyzer profile the plugin itself uses. -->
<TreatWarningsAsErrors>false</TreatWarningsAsErrors>
<AnalysisMode>Default</AnalysisMode>
<GenerateDocumentationFile>false</GenerateDocumentationFile>
<NoWarn>$(NoWarn);CA1707;SA0001;CS1591</NoWarn>
<!--
The plugin targets net9.0 to match Jellyfin 10.11's ABI, but a machine may only have a newer
runtime installed. Rolling the test host forward to the latest major lets the suite run
without pinning developers to a .NET 9 runtime.
-->
<RollForward>LatestMajor</RollForward>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.11.1" />
<PackageReference Include="xunit" Version="2.9.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.2" />
<PackageReference Include="Moq" Version="4.20.72" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="../Jellyfin.Plugin.WatchedTogether/Jellyfin.Plugin.WatchedTogether.csproj" />
</ItemGroup>
<ItemGroup>
<!--
The plugin excludes the runtime assets of these packages because the Jellyfin server supplies
them at load time. Tests run without a server, so they need the real assemblies copied to the
output directory.
-->
<PackageReference Include="Jellyfin.Controller" Version="10.11.5" />
<PackageReference Include="Jellyfin.Model" Version="10.11.5" />
</ItemGroup>
</Project>
@@ -0,0 +1,74 @@
using System;
using System.IO;
using Jellyfin.Plugin.WatchedTogether.Configuration;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Model.Serialization;
using Moq;
using Xunit;
namespace Jellyfin.Plugin.WatchedTogether.Tests;
/// <summary>
/// Marks tests that read or write the process-wide <see cref="Plugin.Instance"/>, so xUnit runs
/// them serially rather than letting parallel classes clobber each other's configuration.
/// </summary>
[CollectionDefinition(nameof(PluginTestContext))]
public class PluginTestCollection : ICollectionFixture<object>
{
}
/// <summary>
/// Constructs a real <see cref="Plugin"/> backed by a temporary directory so that services reading
/// <see cref="Plugin.Instance"/> have configuration to work with, and cleans up afterwards.
/// </summary>
public sealed class PluginTestContext : IDisposable
{
private readonly string _configDirectory;
private PluginTestContext(Plugin plugin, string configDirectory)
{
Plugin = plugin;
_configDirectory = configDirectory;
}
public Plugin Plugin { get; }
public PluginConfiguration Configuration => Plugin.Configuration;
public static PluginTestContext Create()
{
var dir = Path.Combine(Path.GetTempPath(), "wt-tests-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(dir);
// BasePlugin<T> derives its data folder from PluginsPath and its config file from
// PluginConfigurationsPath, so both must resolve to a real directory.
var paths = new Mock<IApplicationPaths>();
paths.SetupGet(p => p.PluginConfigurationsPath).Returns(dir);
paths.SetupGet(p => p.PluginsPath).Returns(dir);
// BasePlugin persists configuration through the serializer; a stub keeps tests off disk
// while still letting UpdateConfiguration succeed.
var serializer = new Mock<IXmlSerializer>();
serializer.Setup(s => s.DeserializeFromFile(It.IsAny<Type>(), It.IsAny<string>()))
.Returns(new PluginConfiguration());
var plugin = new Plugin(paths.Object, serializer.Object);
return new PluginTestContext(plugin, dir);
}
public void Dispose()
{
try
{
if (Directory.Exists(_configDirectory))
{
Directory.Delete(_configDirectory, recursive: true);
}
}
catch (IOException)
{
// A leftover temp directory is not worth failing a test over.
}
}
}
@@ -0,0 +1,53 @@
using System;
using System.Collections.Generic;
using MediaBrowser.Model.Cryptography;
namespace Jellyfin.Plugin.WatchedTogether.Tests;
/// <summary>
/// A crypto provider that accepts exactly the (stored hash, submitted password) pairs it is given.
/// </summary>
/// <remarks>
/// Hand-written rather than mocked: <see cref="ICryptoProvider.Verify"/> takes a
/// <c>ReadOnlySpan&lt;char&gt;</c>, and a ref struct cannot be used as a generic type argument to
/// Moq's <c>It.IsAny&lt;T&gt;</c>.
/// </remarks>
public sealed class StubCryptoProvider : ICryptoProvider
{
private readonly IReadOnlyList<(string Hash, string Password)> _validPairs;
public StubCryptoProvider(IReadOnlyList<(string Hash, string Password)> validPairs)
{
_validPairs = validPairs;
}
public string DefaultHashMethod => "PBKDF2-SHA512";
public bool Verify(PasswordHash hash, ReadOnlySpan<char> password)
{
var candidate = password.ToString();
// Identify the stored credential by its salt rather than by re-formatting the whole hash,
// which need not round-trip through Parse/ToString byte for byte.
var salt = Convert.ToHexString(hash.Salt);
foreach (var (validHash, validPassword) in _validPairs)
{
var expectedSalt = validHash.Split('$')[3];
if (string.Equals(salt, expectedSalt, StringComparison.OrdinalIgnoreCase)
&& candidate == validPassword)
{
return true;
}
}
return false;
}
public PasswordHash CreatePasswordHash(ReadOnlySpan<char> password)
=> throw new NotSupportedException();
public byte[] GenerateSalt() => throw new NotSupportedException();
public byte[] GenerateSalt(int length) => throw new NotSupportedException();
}
@@ -0,0 +1,221 @@
using System;
using System.Collections.Generic;
using System.Threading;
using Jellyfin.Database.Implementations.Entities;
using Jellyfin.Plugin.WatchedTogether.Configuration;
using Jellyfin.Plugin.WatchedTogether.Services;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Model.Entities;
using Microsoft.Extensions.Logging.Abstractions;
using Moq;
using Xunit;
namespace Jellyfin.Plugin.WatchedTogether.Tests;
/// <summary>
/// Covers propagation of played state from a shared account to its members.
/// </summary>
public class WatchedStateSyncTests
{
private static readonly Guid SharedId = Guid.NewGuid();
private sealed class Harness
{
public Mock<IUserDataManager> UserData { get; } = new();
public Mock<IGroupService> Groups { get; } = new();
public List<(User Member, bool Played, int PlayCount)> Saves { get; } = new();
public WatchedStateSyncService Service { get; private set; } = null!;
public static Harness Create(
SharedGroup? group,
IReadOnlyList<User> members,
bool memberAlreadyPlayed = false,
int memberPlayCount = 0)
{
var h = new Harness();
h.Groups.Setup(g => g.GetGroupForSharedUser(It.IsAny<Guid>())).Returns(group);
h.Groups.Setup(g => g.GetEligibleMembers(It.IsAny<SharedGroup>())).Returns(members);
h.UserData.Setup(m => m.GetUserData(It.IsAny<User>(), It.IsAny<BaseItem>()))
.Returns(() => new UserItemData
{
Key = "k",
Played = memberAlreadyPlayed,
PlayCount = memberPlayCount
});
h.UserData.Setup(m => m.SaveUserData(
It.IsAny<User>(),
It.IsAny<BaseItem>(),
It.IsAny<UserItemData>(),
It.IsAny<UserDataSaveReason>(),
It.IsAny<CancellationToken>()))
.Callback<User, BaseItem, UserItemData, UserDataSaveReason, CancellationToken>(
(u, _, d, _, _) => h.Saves.Add((u, d.Played, d.PlayCount)));
h.Service = new WatchedStateSyncService(
h.UserData.Object,
new Mock<IUserManager>().Object,
h.Groups.Object,
NullLogger<WatchedStateSyncService>.Instance);
return h;
}
/// <summary>
/// Raises UserDataSaved as the server would, by starting the service so it subscribes.
/// </summary>
public void Raise(Guid userId, bool played, UserDataSaveReason reason)
{
Service.StartAsync(CancellationToken.None).GetAwaiter().GetResult();
UserData.Raise(
m => m.UserDataSaved += null,
new UserDataSaveEventArgs
{
UserId = userId,
Item = new Folder { Name = "Some Item" },
UserData = new UserItemData { Key = "k", Played = played },
SaveReason = reason
});
Service.StopAsync(CancellationToken.None).GetAwaiter().GetResult();
}
}
private static User MakeUser(string name) => new(name, "Prov", "ResetProv");
private static SharedGroup MakeGroup(bool syncUnwatched = true, bool syncPlayCount = false)
=> new()
{
SharedUserId = SharedId,
MemberUserIds = [Guid.NewGuid(), Guid.NewGuid()],
SyncUnwatched = syncUnwatched,
SyncPlayCount = syncPlayCount
};
[Fact]
public void Played_PropagatesToEveryMember()
{
var alice = MakeUser("alice");
var bob = MakeUser("bob");
var h = Harness.Create(MakeGroup(), [alice, bob]);
h.Raise(SharedId, true, UserDataSaveReason.PlaybackFinished);
Assert.Equal(2, h.Saves.Count);
Assert.All(h.Saves, s => Assert.True(s.Played));
}
[Fact]
public void WritesFromAMember_AreIgnored()
{
// The loop guard: a member's own save must not be treated as a shared-account change.
// GetGroupForSharedUser returns null for any id that is not a shared account.
var h = Harness.Create(null, []);
h.Raise(Guid.NewGuid(), true, UserDataSaveReason.PlaybackFinished);
Assert.Empty(h.Saves);
}
[Theory]
[InlineData(UserDataSaveReason.PlaybackStart)]
[InlineData(UserDataSaveReason.PlaybackProgress)]
[InlineData(UserDataSaveReason.UpdateUserRating)]
public void IrrelevantSaveReasons_AreIgnored(UserDataSaveReason reason)
{
// UserDataSaved fires constantly during playback; only watched-state changes matter.
var h = Harness.Create(MakeGroup(), [MakeUser("alice")]);
h.Raise(SharedId, true, reason);
Assert.Empty(h.Saves);
}
[Fact]
public void Unwatched_PropagatesWhenSyncUnwatchedEnabled()
{
var h = Harness.Create(MakeGroup(syncUnwatched: true), [MakeUser("alice")], memberAlreadyPlayed: true);
h.Raise(SharedId, false, UserDataSaveReason.TogglePlayed);
Assert.Single(h.Saves);
Assert.False(h.Saves[0].Played);
}
[Fact]
public void Unwatched_IsSuppressedWhenSyncUnwatchedDisabled()
{
var h = Harness.Create(MakeGroup(syncUnwatched: false), [MakeUser("alice")], memberAlreadyPlayed: true);
h.Raise(SharedId, false, UserDataSaveReason.TogglePlayed);
Assert.Empty(h.Saves);
}
[Fact]
public void RedundantWrites_AreSuppressed()
{
// The member already matches the shared account, so there is nothing to write.
var h = Harness.Create(MakeGroup(), [MakeUser("alice")], memberAlreadyPlayed: true);
h.Raise(SharedId, true, UserDataSaveReason.PlaybackFinished);
Assert.Empty(h.Saves);
}
[Fact]
public void PlayCount_IsRaisedWhenEnabled()
{
var h = Harness.Create(MakeGroup(syncPlayCount: true), [MakeUser("alice")]);
h.Raise(SharedId, true, UserDataSaveReason.PlaybackFinished);
Assert.Single(h.Saves);
Assert.Equal(1, h.Saves[0].PlayCount);
}
[Fact]
public void PlayCount_IsNotDecrementedForAlreadyWatchedItems()
{
// A member who has watched something five times keeps that count.
var h = Harness.Create(
MakeGroup(syncPlayCount: true),
[MakeUser("alice")],
memberAlreadyPlayed: false,
memberPlayCount: 5);
h.Raise(SharedId, true, UserDataSaveReason.PlaybackFinished);
Assert.Single(h.Saves);
Assert.Equal(5, h.Saves[0].PlayCount);
}
[Fact]
public void PlayCount_IsLeftAloneWhenDisabled()
{
var h = Harness.Create(MakeGroup(syncPlayCount: false), [MakeUser("alice")]);
h.Raise(SharedId, true, UserDataSaveReason.PlaybackFinished);
Assert.Single(h.Saves);
Assert.Equal(0, h.Saves[0].PlayCount);
}
[Fact]
public void DisabledGroup_DoesNotSync()
{
// GetGroupForSharedUser returns null for suspended groups.
var h = Harness.Create(null, [MakeUser("alice")]);
h.Raise(SharedId, true, UserDataSaveReason.PlaybackFinished);
Assert.Empty(h.Saves);
}
}