Merge branch 'master' into fix-code-migration

This commit is contained in:
Cody Robibero
2026-09-06 07:34:30 -04:00
committed by GitHub
33 changed files with 1439 additions and 119 deletions
@@ -0,0 +1,40 @@
using MediaBrowser.Common.Configuration;
using MediaBrowser.Controller.IO;
using MediaBrowser.Controller.MediaEncoding;
using Moq;
using Xunit;
using IConfiguration = Microsoft.Extensions.Configuration.IConfiguration;
namespace Jellyfin.Controller.Tests.MediaEncoding;
public class EncodingHelperInferAudioCodecTests
{
[Theory]
// Manifests and other containers that carry no inferable audio codec.
[InlineData("m3u8", "aac")]
[InlineData("mpd", "aac")]
[InlineData("wtv", "aac")]
[InlineData("", "aac")]
// Containers with a well known audio codec.
[InlineData("mp4", "aac")]
[InlineData("mkv", "aac")]
[InlineData("webm", "opus")]
[InlineData("ts", "mp3")]
// Containers named after the codec they carry.
[InlineData("flac", "flac")]
[InlineData("opus", "opus")]
[InlineData("ac3", "ac3")]
public void InferAudioCodec_ReturnsAnAudioCodec(string container, string expected)
{
Assert.Equal(expected, Create().InferAudioCodec(container));
}
private static EncodingHelper Create()
=> new(
Mock.Of<IApplicationPaths>(),
Mock.Of<IMediaEncoder>(),
Mock.Of<ISubtitleEncoder>(),
Mock.Of<IConfiguration>(),
Mock.Of<IConfigurationManager>(),
Mock.Of<IPathManager>());
}
@@ -0,0 +1,72 @@
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Jellyfin.LiveTv.TunerHosts;
using MediaBrowser.Common.Net;
using MediaBrowser.Controller;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.LiveTv;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.LiveTv;
using MediaBrowser.Model.MediaInfo;
using Microsoft.Extensions.Logging;
using Moq;
using Xunit;
namespace Jellyfin.LiveTv.Tests
{
public class M3UTunerHostTests
{
[Theory]
// A manifest is not a byte stream, so it must never be offered for direct play.
[InlineData("http://example.com/live/1234.m3u8", false)]
[InlineData("http://example.com/live/1234.m3u8?token=abc", false)]
[InlineData("http://example.com/live/1234.mpd", false)]
// Byte streams are unaffected.
[InlineData("http://example.com/live/1234.ts", true)]
[InlineData("http://example.com/live/1234", true)]
public async Task GetChannelStreamMediaSources_ManifestPath_DisablesDirectPlay(string path, bool expectDirectPlay)
{
var mediaSourceManager = new Mock<IMediaSourceManager>();
mediaSourceManager.Setup(x => x.GetPathProtocol(It.IsAny<string>())).Returns(MediaProtocol.Http);
var host = new TestableM3UTunerHost(
Mock.Of<IServerConfigurationManager>(),
mediaSourceManager.Object,
Mock.Of<ILogger<M3UTunerHost>>(),
Mock.Of<IFileSystem>(),
Mock.Of<IHttpClientFactory>(),
Mock.Of<IServerApplicationHost>(),
Mock.Of<INetworkManager>(),
Mock.Of<IStreamHelper>());
var sources = await host.GetMediaSources(
new TunerHostInfo { TunerCount = 0, EnableStreamLooping = false },
new ChannelInfo { Path = path });
Assert.Equal(expectDirectPlay, sources[0].SupportsDirectPlay);
}
private sealed class TestableM3UTunerHost : M3UTunerHost
{
public TestableM3UTunerHost(
IServerConfigurationManager config,
IMediaSourceManager mediaSourceManager,
ILogger<M3UTunerHost> logger,
IFileSystem fileSystem,
IHttpClientFactory httpClientFactory,
IServerApplicationHost appHost,
INetworkManager networkManager,
IStreamHelper streamHelper)
: base(config, mediaSourceManager, logger, fileSystem, httpClientFactory, appHost, networkManager, streamHelper)
{
}
public Task<List<MediaSourceInfo>> GetMediaSources(TunerHostInfo tuner, ChannelInfo channel)
=> GetChannelStreamMediaSources(tuner, channel, CancellationToken.None);
}
}
}
@@ -0,0 +1,103 @@
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.MediaEncoding.Encoder;
using MediaBrowser.Model.Globalization;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.MediaInfo;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Moq;
using Xunit;
namespace Jellyfin.MediaEncoding.Tests.Encoder;
public class ProcessWrapperTests
{
[Fact]
public async Task ExitedProcess_StaysUsableForTheCallerThatStartedIt()
{
using var process = CreateProcess();
using var exitHandled = new ManualResetEventSlim(false);
using (var wrapper = new MediaEncoder.ProcessWrapper(process, CreateEncoder()))
{
// Subscribed after the wrapper, so by the time this is set the wrapper's own handler has
// already run: whatever it does to the process has happened.
process.Exited += (_, _) => exitHandled.Set();
process.Start();
await process.WaitForExitAsync(TestContext.Current.CancellationToken).ConfigureAwait(true);
Assert.True(exitHandled.Wait(TimeSpan.FromSeconds(15), TestContext.Current.CancellationToken), "The process never raised Exited.");
// The caller still owns the process here. Disposing it from the exit handler handed
// whoever exited quickest an ObjectDisposedException out of these three lines.
var output = await process.StandardOutput.ReadToEndAsync(TestContext.Current.CancellationToken).ConfigureAwait(true);
Assert.Equal("jellyfin", output.Trim());
Assert.True(wrapper.HasExited);
Assert.Equal(3, wrapper.ExitCode);
}
}
[Fact]
public async Task ExitState_IsReadableBeforeTheExitEventArrives()
{
using var process = CreateProcess();
using (var wrapper = new MediaEncoder.ProcessWrapper(process, CreateEncoder()))
{
process.Start();
await process.WaitForExitAsync(TestContext.Current.CancellationToken).ConfigureAwait(true);
// The exit event is raised on the thread pool and can lag behind the wait that just
// returned, so neither of these may depend on it having arrived.
Assert.True(wrapper.HasExited);
Assert.Equal(3, wrapper.ExitCode);
}
}
[Fact]
public async Task ExitCode_SurvivesDisposal()
{
using var process = CreateProcess();
var wrapper = new MediaEncoder.ProcessWrapper(process, CreateEncoder());
process.Start();
await process.WaitForExitAsync(TestContext.Current.CancellationToken).ConfigureAwait(true);
var exitCode = wrapper.ExitCode;
wrapper.Dispose();
Assert.Equal(exitCode, wrapper.ExitCode);
Assert.True(wrapper.HasExited);
}
private static MediaEncoder CreateEncoder()
=> new(
Mock.Of<ILogger<MediaEncoder>>(),
Mock.Of<IServerConfigurationManager>(),
Mock.Of<IFileSystem>(),
Mock.Of<IBlurayExaminer>(),
Mock.Of<ILocalizationManager>(),
new ConfigurationBuilder().Build(),
Mock.Of<IServerConfigurationManager>());
// Writes to stdout and exits immediately with a non-zero code, standing in for the ffprobe that
// rejects a file outright - the process that used to win the race against its own caller.
private static Process CreateProcess()
{
var startInfo = OperatingSystem.IsWindows()
? new ProcessStartInfo("cmd.exe", "/c echo jellyfin & exit 3")
: new ProcessStartInfo("/bin/sh", "-c \"printf 'jellyfin\\n'; exit 3\"");
startInfo.CreateNoWindow = true;
startInfo.UseShellExecute = false;
startInfo.RedirectStandardOutput = true;
return new Process { StartInfo = startInfo, EnableRaisingEvents = true };
}
}
@@ -0,0 +1,104 @@
using System;
using Jellyfin.Data.Enums;
using MediaBrowser.Model.Dlna;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.MediaInfo;
using MediaBrowser.Model.Session;
using Microsoft.Extensions.Logging.Abstractions;
using Moq;
using Xunit;
namespace Jellyfin.Model.Tests.Dlna;
public class StreamBuilderManifestContainerTests
{
[Theory]
// A manifest describes a stream instead of carrying one, so it can never be direct played,
// even when the client claims to support the container.
[InlineData("hls")]
[InlineData("hls,applehttp")]
[InlineData("applehttp")]
[InlineData("dash")]
public void GetOptimalVideoStream_ManifestContainer_DoesNotDirectPlay(string container)
{
var streamInfo = BuildFor(container);
Assert.NotNull(streamInfo);
Assert.Equal(PlayMethod.Transcode, streamInfo.PlayMethod);
}
[Fact]
public void GetOptimalVideoStream_ByteStreamContainer_StillDirectPlays()
{
var streamInfo = BuildFor("mp4");
Assert.NotNull(streamInfo);
Assert.Equal(PlayMethod.DirectPlay, streamInfo.PlayMethod);
}
private static StreamInfo? BuildFor(string container)
{
var mediaSource = new MediaSourceInfo
{
Id = "test-source",
Path = "http://example.com/live/channel",
Protocol = MediaProtocol.Http,
Container = container,
SupportsDirectPlay = true,
SupportsDirectStream = true,
SupportsTranscoding = true,
IsInfiniteStream = true,
IsRemote = true,
MediaStreams =
[
new MediaStream { Type = MediaStreamType.Video, Index = 0, Codec = "h264" },
new MediaStream { Type = MediaStreamType.Audio, Index = 1, Codec = "aac" }
]
};
var profile = new DeviceProfile
{
Name = "Manifest aware client",
DirectPlayProfiles =
[
new DirectPlayProfile
{
Type = DlnaProfileType.Video,
Container = "mp4,hls,applehttp,dash",
VideoCodec = "h264",
AudioCodec = "aac"
}
],
TranscodingProfiles =
[
new TranscodingProfile
{
Type = DlnaProfileType.Video,
Context = EncodingContext.Streaming,
Protocol = MediaStreamProtocol.hls,
Container = "ts",
VideoCodec = "h264",
AudioCodec = "aac"
}
]
};
var options = new MediaOptions
{
ItemId = new Guid("11D229B7-2D48-4B95-9F9B-49F6AB75E613"),
MediaSourceId = mediaSource.Id,
MediaSources = [mediaSource],
DeviceId = "test-deviceId",
Profile = profile,
AllowAudioStreamCopy = true,
AllowVideoStreamCopy = true,
EnableDirectStream = false // This is disabled in server
};
var transcodeSupport = new Mock<ITranscoderSupport>();
return new StreamBuilder(transcodeSupport.Object, new NullLogger<StreamBuilderManifestContainerTests>())
.GetOptimalVideoStream(options);
}
}
@@ -179,6 +179,146 @@ public class MediaInfoResolverTests
Assert.Empty(streams);
}
[Fact]
public void GetExternalFiles_VobSubIdxAndSubPair_OnlyReturnsIdxFile()
{
// VobSub (.sub) payloads only carry per-track language metadata when read
// alongside their paired .idx index file. When both are present, only the
// .idx file should be returned so it (not the raw .sub) gets probed.
BaseItem.MediaSourceManager = Mock.Of<IMediaSourceManager>();
var video = new Movie
{
Path = VideoDirectoryPath + "/My.Video.mkv"
};
var directoryService = new Mock<IDirectoryService>(MockBehavior.Strict);
directoryService.Setup(ds => ds.GetFilePaths(It.IsRegex(VideoDirectoryRegex), It.IsAny<bool>()))
.Returns(new[] { VideoDirectoryPath + "/My.Video.idx", VideoDirectoryPath + "/My.Video.sub" });
directoryService.Setup(ds => ds.GetFilePaths(It.IsRegex(MetadataDirectoryRegex), It.IsAny<bool>()))
.Returns(Array.Empty<string>());
var streams = _subtitleResolver.GetExternalFiles(video, directoryService.Object, false).ToList();
var stream = Assert.Single(streams);
Assert.EndsWith(".idx", stream.Path, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public void GetExternalFiles_VobSubIdxWithoutMatchingSub_DoesNotReturnIdxFile()
{
// An .idx file with no paired .sub cannot be probed for anything, so it must be
// left out entirely rather than surfaced as a doomed-to-fail probe candidate.
// Surfacing it anyway would also make it "exist" from Jellyfin's perspective
// even after the real .sub is deleted, preventing stale subtitle stream data
// from ever being cleared on a rescan.
BaseItem.MediaSourceManager = Mock.Of<IMediaSourceManager>();
var video = new Movie
{
Path = VideoDirectoryPath + "/My.Video.mkv"
};
var directoryService = GetDirectoryServiceForExternalFile("My.Video.idx");
var streams = _subtitleResolver.GetExternalFiles(video, directoryService, false).ToList();
Assert.Empty(streams);
}
[Fact]
public void GetExternalFiles_StandaloneSubWithoutIdx_StillReturnsSubFile()
{
// Guards against the .idx/.sub pairing suppression firing when there is no
// .idx sidecar at all - a lone .sub file must still be returned.
BaseItem.MediaSourceManager = Mock.Of<IMediaSourceManager>();
var video = new Movie
{
Path = VideoDirectoryPath + "/My.Video.mkv"
};
var directoryService = GetDirectoryServiceForExternalFile("My.Video.sub");
var streams = _subtitleResolver.GetExternalFiles(video, directoryService, false).ToList();
var stream = Assert.Single(streams);
Assert.EndsWith(".sub", stream.Path, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public void GetExternalFiles_VobSubIdxAndSubInDifferentDirectories_DoesNotPair()
{
// A same-named .idx and .sub split across the video folder and the internal
// metadata folder cannot be paired by ffprobe (it only looks next to the .idx),
// so the .sub must still be returned, but the orphaned .idx (no sibling .sub in
// its own directory) must be left out since it cannot be probed.
BaseItem.MediaSourceManager = Mock.Of<IMediaSourceManager>();
var video = new Movie
{
Path = VideoDirectoryPath + "/My.Video.mkv"
};
var directoryService = new Mock<IDirectoryService>(MockBehavior.Strict);
directoryService.Setup(ds => ds.GetFilePaths(It.IsRegex(VideoDirectoryRegex), It.IsAny<bool>()))
.Returns(new[] { VideoDirectoryPath + "/My.Video.sub" });
directoryService.Setup(ds => ds.GetFilePaths(It.IsRegex(MetadataDirectoryRegex), It.IsAny<bool>()))
.Returns(new[] { MetadataDirectoryPath + "/My.Video.idx" });
var streams = _subtitleResolver.GetExternalFiles(video, directoryService.Object, false).ToList();
var stream = Assert.Single(streams);
Assert.EndsWith(".sub", stream.Path, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public void GetExternalFiles_VobSubIdxAndSubWithMatchingLanguageFlag_SuppressesSub()
{
// A .idx/.sub pair sharing the same filename flags (e.g. a language token) should
// still pair and suppress the .sub, just like an unflagged pair.
BaseItem.MediaSourceManager = Mock.Of<IMediaSourceManager>();
var video = new Movie
{
Path = VideoDirectoryPath + "/My.Video.mkv"
};
var directoryService = new Mock<IDirectoryService>(MockBehavior.Strict);
directoryService.Setup(ds => ds.GetFilePaths(It.IsRegex(VideoDirectoryRegex), It.IsAny<bool>()))
.Returns(new[] { VideoDirectoryPath + "/My.Video.en.idx", VideoDirectoryPath + "/My.Video.en.sub" });
directoryService.Setup(ds => ds.GetFilePaths(It.IsRegex(MetadataDirectoryRegex), It.IsAny<bool>()))
.Returns(Array.Empty<string>());
var streams = _subtitleResolver.GetExternalFiles(video, directoryService.Object, false).ToList();
var stream = Assert.Single(streams);
Assert.EndsWith(".idx", stream.Path, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public void GetExternalFiles_VobSubIdxAndSubWithMismatchedNames_DoesNotPair()
{
// An .idx and .sub with different basenames (e.g. differing filename flags) are not
// a pair ffprobe would resolve. The .sub must still be returned, but the orphaned
// .idx (no same-named sibling .sub) must be left out since it cannot be probed.
BaseItem.MediaSourceManager = Mock.Of<IMediaSourceManager>();
var video = new Movie
{
Path = VideoDirectoryPath + "/My.Video.mkv"
};
var directoryService = new Mock<IDirectoryService>(MockBehavior.Strict);
directoryService.Setup(ds => ds.GetFilePaths(It.IsRegex(VideoDirectoryRegex), It.IsAny<bool>()))
.Returns(new[] { VideoDirectoryPath + "/My.Video.idx", VideoDirectoryPath + "/My.Video.en.sub" });
directoryService.Setup(ds => ds.GetFilePaths(It.IsRegex(MetadataDirectoryRegex), It.IsAny<bool>()))
.Returns(Array.Empty<string>());
var streams = _subtitleResolver.GetExternalFiles(video, directoryService.Object, false).ToList();
var stream = Assert.Single(streams);
Assert.EndsWith(".sub", stream.Path, StringComparison.OrdinalIgnoreCase);
}
[Theory]
[InlineData("https://url.com/My.Video.mkv")]
[InlineData(VideoDirectoryPath)] // valid but no files found for this test
@@ -0,0 +1,123 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Emby.Server.Implementations.EntryPoints;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Controller.Session;
using MediaBrowser.Model.Configuration;
using Microsoft.Extensions.Logging.Abstractions;
using Moq;
using Xunit;
namespace Jellyfin.Server.Implementations.Tests.EntryPoints;
public class LibraryChangedNotifierTests
{
// How long a test waits for the notifier's timer callback to run. Generous: the assertions are
// about a batch being sent at all, not about how promptly.
private static readonly TimeSpan _flushTimeout = TimeSpan.FromSeconds(15);
private readonly Mock<ILibraryManager> _libraryManager = new();
private readonly Mock<IServerConfigurationManager> _configurationManager = new();
private readonly Mock<ISessionManager> _sessionManager = new();
private readonly Mock<IUserManager> _userManager = new();
private readonly Mock<IProviderManager> _providerManager = new();
private readonly ServerConfiguration _configuration = new();
private int _flushCount;
public LibraryChangedNotifierTests()
{
_configurationManager.SetupGet(e => e.Configuration).Returns(_configuration);
// Reading the session list is the first thing a flush does, so it stands in for "a batch was
// sent" without having to mock a whole user library behind it.
_sessionManager.SetupGet(e => e.Sessions)
.Returns(() =>
{
Interlocked.Increment(ref _flushCount);
return [];
});
}
[Fact]
public async Task OnLibraryItemUpdated_BatchSizeCapReached_SendsWithoutWaitingForWindow()
{
// Long enough that only the size cap can close the batch.
_configuration.LibraryUpdateDuration = 3600;
var notifier = CreateNotifier();
await notifier.StartAsync(TestContext.Current.CancellationToken);
for (var i = 0; i < LibraryChangedNotifier.MaxBatchSize; i++)
{
RaiseItemUpdated();
}
Assert.True(await WaitForFlushAsync(1), "The batch was not sent once it hit the size cap.");
await notifier.StopAsync(TestContext.Current.CancellationToken);
notifier.Dispose();
}
[Fact]
public async Task OnLibraryItemUpdated_ChangesNeverPause_StillSendsOnTheWindow()
{
// A scan changes items continuously. The window must run from the first change of a batch, or
// the batch never closes and holds every item it named alive for the length of the scan.
_configuration.LibraryUpdateDuration = 1;
var notifier = CreateNotifier();
await notifier.StartAsync(TestContext.Current.CancellationToken);
var stopwatch = Stopwatch.StartNew();
while (stopwatch.Elapsed < _flushTimeout && Volatile.Read(ref _flushCount) == 0)
{
// Well below the window, and well below the size cap over the whole loop.
RaiseItemUpdated();
await Task.Delay(25, TestContext.Current.CancellationToken);
}
Assert.True(Volatile.Read(ref _flushCount) > 0, "The batch was never sent while changes kept arriving.");
await notifier.StopAsync(TestContext.Current.CancellationToken);
notifier.Dispose();
}
private LibraryChangedNotifier CreateNotifier()
=> new(
_libraryManager.Object,
_configurationManager.Object,
_sessionManager.Object,
_userManager.Object,
NullLogger<LibraryChangedNotifier>.Instance,
_providerManager.Object);
// A folder passes the notifier's item filter without needing any of BaseItem's static services.
private void RaiseItemUpdated()
=> _libraryManager.Raise(
e => e.ItemUpdated += null,
_libraryManager.Object,
new ItemChangeEventArgs { Item = new Folder { Id = Guid.NewGuid() } });
private async Task<bool> WaitForFlushAsync(int expected)
{
var stopwatch = Stopwatch.StartNew();
while (stopwatch.Elapsed < _flushTimeout)
{
if (Volatile.Read(ref _flushCount) >= expected)
{
return true;
}
await Task.Delay(25, TestContext.Current.CancellationToken);
}
return false;
}
}
@@ -0,0 +1,78 @@
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Emby.Server.Implementations.EntryPoints;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Session;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Session;
using Moq;
using Xunit;
namespace Jellyfin.Server.Implementations.Tests.EntryPoints;
public class UserDataChangeNotifierTests
{
// How long a test waits for the notifier's timer callback to run. Generous: the assertions are
// about a batch being sent at all, not about how promptly.
private static readonly TimeSpan _flushTimeout = TimeSpan.FromSeconds(15);
private readonly Mock<IUserDataManager> _userDataManager = new();
private readonly Mock<ISessionManager> _sessionManager = new();
private readonly Mock<IUserManager> _userManager = new();
private int _flushCount;
public UserDataChangeNotifierTests()
{
_sessionManager
.Setup(e => e.SendMessageToUserSessions(
It.IsAny<System.Collections.Generic.List<Guid>>(),
SessionMessageType.UserDataChanged,
It.IsAny<Func<UserDataChangeInfo>>(),
It.IsAny<CancellationToken>()))
.Callback(() => Interlocked.Increment(ref _flushCount))
.Returns(Task.CompletedTask);
}
[Fact]
public async Task OnUserDataSaved_ChangesNeverPause_StillSendsOnTheWindow()
{
// A scan changes user data continuously. The window must run from the first change of a batch,
// or the batch never closes and holds every item it named alive for the length of the scan.
var notifier = CreateNotifier();
await notifier.StartAsync(TestContext.Current.CancellationToken);
var userId = Guid.NewGuid();
var stopwatch = Stopwatch.StartNew();
while (stopwatch.Elapsed < _flushTimeout && Volatile.Read(ref _flushCount) == 0)
{
// Well below the window, and well below the size cap over the whole loop.
RaiseUserDataSaved(userId);
await Task.Delay(25, TestContext.Current.CancellationToken);
}
Assert.True(Volatile.Read(ref _flushCount) > 0, "The batch was never sent while changes kept arriving.");
await notifier.StopAsync(TestContext.Current.CancellationToken);
notifier.Dispose();
}
private UserDataChangeNotifier CreateNotifier()
=> new(_userDataManager.Object, _sessionManager.Object, _userManager.Object);
// A folder needs none of BaseItem's static services, and PlaybackProgress is the one reason the
// notifier ignores outright.
private void RaiseUserDataSaved(Guid userId)
=> _userDataManager.Raise(
e => e.UserDataSaved += null,
_userDataManager.Object,
new UserDataSaveEventArgs
{
UserId = userId,
SaveReason = UserDataSaveReason.UpdateUserRating,
Item = new Folder { Id = Guid.NewGuid() }
});
}
@@ -0,0 +1,77 @@
using System;
using System.Linq;
using System.Threading.Tasks;
using Jellyfin.Database.Implementations.Entities;
using Jellyfin.Server.Implementations.Item;
using MediaBrowser.Controller;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Model.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging.Abstractions;
using Moq;
using Xunit;
namespace Jellyfin.Server.Implementations.Tests.Item;
public class ItemPersistenceServiceSaveImagesTests : SqliteDbTestFixture
{
private readonly ItemPersistenceService _service;
public ItemPersistenceServiceSaveImagesTests()
{
_service = new ItemPersistenceService(
CreateDbContextFactory(),
Mock.Of<IServerApplicationHost>(),
NullLogger<ItemPersistenceService>.Instance);
}
[Fact]
public async Task SaveImagesAsync_ReplacesThePreviousImages()
{
var itemId = Guid.NewGuid();
Seed(itemId);
await _service.SaveImagesAsync(CreateItem(itemId, "/first.jpg"), TestContext.Current.CancellationToken);
await _service.SaveImagesAsync(CreateItem(itemId, "/second.jpg"), TestContext.Current.CancellationToken);
using var context = CreateDbContext();
var paths = context.BaseItemImageInfos
.Where(e => e.ItemId.Equals(itemId))
.Select(e => e.Path)
.ToList();
Assert.Equal(["/second.jpg"], paths);
}
[Fact]
public async Task SaveImagesAsync_ItemDeletedFromUnderIt_IsANoOp()
{
// A scan can delete the item between the refresh reading it and the images being written. That
// must not fail the whole refresh, and must not leave the images of an item that is gone.
var itemId = Guid.NewGuid();
await _service.SaveImagesAsync(CreateItem(itemId, "/gone.jpg"), TestContext.Current.CancellationToken);
using var context = CreateDbContext();
Assert.Empty(context.BaseItemImageInfos.Where(e => e.ItemId.Equals(itemId)));
}
private static BaseItem CreateItem(Guid itemId, string imagePath)
=> new Folder
{
Id = itemId,
ImageInfos = [new ItemImageInfo { Path = imagePath, Type = ImageType.Primary }]
};
private void Seed(Guid itemId)
{
using var context = CreateDbContext();
context.BaseItems.Add(new BaseItemEntity
{
Id = itemId,
Type = "Folder",
IsFolder = true
});
context.SaveChanges();
}
}
@@ -1,4 +1,5 @@
using System;
using System.Threading;
using Emby.Server.Implementations.Data;
using Jellyfin.Database.Implementations;
using Jellyfin.Database.Implementations.Locking;
@@ -58,6 +59,8 @@ public abstract class SqliteDbTestFixture : IDisposable
{
var factory = new Mock<IDbContextFactory<JellyfinDbContext>>();
factory.Setup(f => f.CreateDbContext()).Returns(CreateDbContext);
factory.Setup(f => f.CreateDbContextAsync(It.IsAny<CancellationToken>()))
.ReturnsAsync(CreateDbContext);
return factory.Object;
}
@@ -142,6 +142,36 @@ public class PlayQueueManagerTests
Assert.Equal(Guid.Empty, queue.GetPlayingItemPlaylistId());
}
[Fact]
public void SetShuffleMode_SortedWhileAlreadySorted_KeepsPlayingItem()
{
var queue = CreateQueue(3);
queue.SetPlayingItemByIndex(1);
var expectedItemId = queue.GetPlayingItemId();
queue.SetShuffleMode(GroupShuffleMode.Sorted);
Assert.Equal(GroupShuffleMode.Sorted, queue.ShuffleMode);
Assert.Equal(1, queue.PlayingItemIndex);
Assert.Equal(expectedItemId, queue.GetPlayingItemId());
}
[Fact]
public void SetShuffleMode_SortedTwiceAfterShuffle_KeepsPlayingItem()
{
var queue = CreateQueue(5);
queue.SetPlayingItemByIndex(2);
var expectedItemId = queue.GetPlayingItemId();
queue.SetShuffleMode(GroupShuffleMode.Shuffle);
queue.SetShuffleMode(GroupShuffleMode.Sorted);
queue.SetShuffleMode(GroupShuffleMode.Sorted);
Assert.Equal(GroupShuffleMode.Sorted, queue.ShuffleMode);
Assert.Equal(5, queue.GetPlaylist().Count);
Assert.Equal(expectedItemId, queue.GetPlayingItemId());
}
[Fact]
public void SetPlayingItemByIndex_InBounds_SetsPlayingItem()
{
@@ -0,0 +1,95 @@
using System;
using System.Threading;
using Jellyfin.Database.Implementations.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Session;
using MediaBrowser.Controller.SyncPlay.Requests;
using Microsoft.Extensions.Logging.Abstractions;
using Moq;
using Xunit;
using SyncPlayManager = Emby.Server.Implementations.SyncPlay.SyncPlayManager;
namespace Jellyfin.Server.Implementations.Tests.SyncPlay;
public class SyncPlayManagerTests
{
[Fact]
public void LeaveGroup_AfterJoiningTheSameGroupTwice_ClearsTheActiveSessionCounter()
{
var harness = new ManagerHarness();
var info = harness.Manager.NewGroup(harness.Session, new NewGroupRequest("group"), CancellationToken.None);
Assert.True(harness.Manager.IsUserActive(harness.User.Id));
// A client that re-sends Join for the group it is already in must not be counted twice.
harness.Manager.JoinGroup(harness.Session, new JoinGroupRequest(info.GroupId), CancellationToken.None);
harness.Manager.LeaveGroup(harness.Session, new LeaveGroupRequest(), CancellationToken.None);
Assert.False(harness.Manager.IsUserActive(harness.User.Id));
}
[Fact]
public void LeaveGroup_AfterASingleJoin_ClearsTheActiveSessionCounter()
{
var harness = new ManagerHarness();
harness.Manager.NewGroup(harness.Session, new NewGroupRequest("group"), CancellationToken.None);
harness.Manager.LeaveGroup(harness.Session, new LeaveGroupRequest(), CancellationToken.None);
Assert.False(harness.Manager.IsUserActive(harness.User.Id));
}
[Fact]
public void IsUserActive_WithTwoSessionsOfTheSameUser_TracksBothSeparately()
{
var harness = new ManagerHarness();
var second = harness.CreateSession("session-2");
var info = harness.Manager.NewGroup(harness.Session, new NewGroupRequest("group"), CancellationToken.None);
harness.Manager.JoinGroup(second, new JoinGroupRequest(info.GroupId), CancellationToken.None);
harness.Manager.LeaveGroup(harness.Session, new LeaveGroupRequest(), CancellationToken.None);
Assert.True(harness.Manager.IsUserActive(harness.User.Id));
harness.Manager.LeaveGroup(second, new LeaveGroupRequest(), CancellationToken.None);
Assert.False(harness.Manager.IsUserActive(harness.User.Id));
}
private sealed class ManagerHarness
{
private readonly Mock<ISessionManager> _sessionManager = new();
public ManagerHarness()
{
var userManager = new Mock<IUserManager>();
var libraryManager = new Mock<ILibraryManager>();
User = new User("tester", "auth-provider", "pwdreset-provider");
userManager.Setup(m => m.GetUserById(It.IsAny<Guid>())).Returns(User);
Manager = new SyncPlayManager(
NullLoggerFactory.Instance,
userManager.Object,
_sessionManager.Object,
libraryManager.Object);
Session = CreateSession("session-1");
}
public SyncPlayManager Manager { get; }
public User User { get; }
public SessionInfo Session { get; }
public SessionInfo CreateSession(string id)
{
return new SessionInfo(_sessionManager.Object, NullLogger.Instance)
{
Id = id,
UserId = User.Id,
UserName = User.Username
};
}
}
}
@@ -0,0 +1,141 @@
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Jellyfin.Database.Implementations.Entities;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Session;
using MediaBrowser.Controller.SyncPlay.GroupStates;
using MediaBrowser.Controller.SyncPlay.PlaybackRequests;
using MediaBrowser.Controller.SyncPlay.Requests;
using MediaBrowser.Model.SyncPlay;
using Microsoft.Extensions.Logging.Abstractions;
using Moq;
using Xunit;
using SyncPlayGroup = Emby.Server.Implementations.SyncPlay.Group;
namespace Jellyfin.Server.Implementations.Tests.SyncPlay;
public class WaitingGroupStateTests
{
[Fact]
public void Ready_ClientResumedWithLowPing_AppliesTheDefaultPingFloorInMilliseconds()
{
var harness = new GroupHarness();
var group = harness.Group;
// Both members report a ping well under the default, so the floor is what decides the delay.
group.UpdatePing(harness.First, 10);
group.UpdatePing(harness.Second, 10);
group.PositionTicks = TimeSpan.FromMinutes(5).Ticks;
group.LastActivity = DateTime.UtcNow;
group.SetBuffering(harness.First, true);
group.SetBuffering(harness.Second, false);
var state = new WaitingGroupState(NullLoggerFactory.Instance) { ResumePlaying = true };
var before = DateTime.UtcNow;
state.HandleRequest(
new ReadyGroupRequest(DateTime.UtcNow, group.PositionTicks, true, harness.PlaylistItemId),
group,
GroupStateType.Waiting,
harness.First,
CancellationToken.None);
// DefaultPing is expressed in milliseconds, so the floor must be converted before being
// compared against a tick count. Without the conversion the floor is 500 ticks (0.05 ms)
// and never applies.
var scheduledDelay = group.LastActivity - before;
Assert.True(
scheduledDelay >= TimeSpan.FromMilliseconds(group.DefaultPing),
$"expected a resume delay of at least {group.DefaultPing} ms, got {scheduledDelay.TotalMilliseconds} ms");
}
[Theory]
[InlineData(4_000_000_000L)]
[InlineData(1_000_000_000_000_000L)]
[InlineData(long.MaxValue)]
[InlineData(-1L)]
public void UpdatePing_ClientReportsAnUnusablePing_IsClampedAndCannotStallTheGroup(long reportedPing)
{
var harness = new GroupHarness();
var group = harness.Group;
group.UpdatePing(harness.First, reportedPing);
Assert.InRange(group.GetHighestPing(), 0, group.MaxPing);
// The reported ping is scaled into the group's resume point, so an unclamped value either
// pushes playback months out or overflows the arithmetic outright.
var state = new PlayingGroupState(NullLoggerFactory.Instance);
var before = DateTime.UtcNow;
state.HandleRequest(
new UnpauseGroupRequest(),
group,
GroupStateType.Paused,
harness.First,
CancellationToken.None);
Assert.InRange(group.LastActivity - before, TimeSpan.Zero, TimeSpan.FromMinutes(1));
}
private sealed class GroupHarness
{
public GroupHarness()
{
var userManager = new Mock<IUserManager>();
var sessionManager = new Mock<ISessionManager>();
var libraryManager = new Mock<ILibraryManager>();
var user = new User("tester", "auth-provider", "pwdreset-provider");
userManager.Setup(m => m.GetUserById(It.IsAny<Guid>())).Returns(user);
var item = new Mock<BaseItem>();
item.Setup(i => i.IsVisibleStandalone(It.IsAny<User>())).Returns(true);
item.Object.RunTimeTicks = TimeSpan.FromHours(2).Ticks;
libraryManager.Setup(m => m.GetItemById(It.IsAny<Guid>())).Returns(item.Object);
sessionManager
.Setup(m => m.SendSyncPlayCommand(It.IsAny<string>(), It.IsAny<SendCommand>(), It.IsAny<CancellationToken>()))
.Returns(Task.CompletedTask);
sessionManager
.Setup(m => m.SendSyncPlayGroupUpdate(It.IsAny<string>(), It.IsAny<GroupUpdate<GroupStateUpdate>>(), It.IsAny<CancellationToken>()))
.Returns(Task.CompletedTask);
Group = new SyncPlayGroup(
NullLoggerFactory.Instance,
userManager.Object,
sessionManager.Object,
libraryManager.Object);
First = new SessionInfo(sessionManager.Object, NullLogger.Instance)
{
Id = "first",
UserId = user.Id,
UserName = "first"
};
Second = new SessionInfo(sessionManager.Object, NullLogger.Instance)
{
Id = "second",
UserId = user.Id,
UserName = "second"
};
Group.CreateGroup(First, new NewGroupRequest("group"), CancellationToken.None);
Group.SessionJoin(Second, new JoinGroupRequest(Group.GroupId), CancellationToken.None);
Group.SetPlayQueue(new List<Guid> { Guid.NewGuid() }, 0, 0);
PlaylistItemId = Group.PlayQueue.GetPlayingItemPlaylistId();
}
public SyncPlayGroup Group { get; }
public SessionInfo First { get; }
public SessionInfo Second { get; }
public Guid PlaylistItemId { get; }
}
}